1. Introduction
The purpose of this document is to specify an algorithm for resolving the location of external style sheets included by the @import rule in Sass tooling. It is written for developers and implementors looking for formal guidance, and should match existing implementions.
1.1. The @import rule
The @import rule allows users to import style rules from other style sheets. If an @import rule refers to a valid stylesheet, user agents must treat the contents of the stylesheet as if they were written in place of the @import rule, with two exceptions:
- If a feature *explicitly* defines that it only applies to a particular stylesheet, and not any imported ones (such as the @namespace rule), then it doesn’t apply to the imported stylesheet.
- If a feature relies on the relative position of two or more constructs in a stylesheet (such as the requirement that an @else rule follow another conditional group rule, or the requirement that @charset must not have any other content preceding it), it only applies between constructs in the same stylesheet.
Any @import rules must precede all other at-rules and style rules in a style sheet (besides @charset, which must be the first thing in the style sheet if it exists), or else the @import rule is invalid.
2. Resolve Algorithm
When @import is called, the following high-level algorithm is used to
resolve the location of a file within url(id)
from cwd
:
-
if
id
begins with/
-
cwd
is the filesystem root
-
-
file
iscwd/id
-
base
is base path offile
-
dir
is directory path offile
-
if
base
ends with.sass
,.scss
, or.css
-
test whether
file
exists -
if
base
does not start with_
-
test whether
dir/_base
exists
-
-
-
otherwise
-
test whether
dir/base.scss
exists -
test whether
dir/base.sass
exists -
test whether
dir/base.css
exists -
if
base
does not start with_
-
test whether
dir/_base.scss
exists -
test whether
dir/_base.sass
exists -
test whether
dir/_base.css
exists
-
-
-
if the length of existing files is
1
-
return the existing file
-
-
otherwise, if the length of existing files is greater than
1
-
throw
"It’s not clear which file to import"
-
-
otherwise, if
base
does not end with.css
-
throw
"File to import not found or unreadable"
-
3. Implementations
Parcelify is a tool to add css to your npm modules consumed with browserify. It includes the Resolve Algorithm internally.
PostCSS Import is a
PostCSS plugin to transform @import rules by inlining content. It includes
the Resolve Algorithm internally, but diverges from the load_as_directory algorithm by using the style
field and
then the main
field if possible.
rework-npm is a tool to import CSS styles from NPM modules using rework. It includes the Resolve Algorithm internally, but diverges by supporting glob notation.