@import

Sass 扩展了 CSS@import 规则,能够导入 Sass 和 CSS 样式表,提供对 混入函数变量 的访问,并将多个样式表的 CSS 组合在一起。与普通 CSS 导入(要求浏览器在渲染页面时发出多个 HTTP 请求)不同,Sass 导入完全在编译期间处理。

Sass 导入与 CSS 导入具有相同的语法,不同之处在于它们允许用逗号分隔多个导入,而不是要求每个导入都有自己的 @import。此外,在 缩进语法 中,导入的 URL 不需要包含引号。

¥Sass imports have the same syntax as CSS imports, except that they allow multiple imports to be separated by commas rather than requiring each one to have its own @import. Also, in the indented syntax, imported URLs aren’t required to have quotes.

⚠️ Heads up!

Sass 团队不鼓励继续使用 @import 规则。Sass 将在未来几年内进行 逐步淘汰 版本,并最终将其从语言中完全删除。更喜欢 @use 规则。(请注意,目前只有 Dart Sass 支持 @use。其他实现的用户必须使用 @import 规则。)

¥The Sass team discourages the continued use of the @import rule. Sass will gradually phase it out over the next few years, and eventually remove it from the language entirely. Prefer the @use rule instead. (Note that only Dart Sass currently supports @use. Users of other implementations must use the @import rule instead.)

What’s Wrong With @import?

@import 规则有许多严重的问题:

¥The @import rule has a number of serious issues:

  • @import 使所有变量、mixins 和函数都可以全局访问。这使得人们(或工具)很难判断任何内容是在哪里定义的。

    ¥@import makes all variables, mixins, and functions globally accessible. This makes it very difficult for people (or tools) to tell where anything is defined.

  • 因为一切都是全局的,所以库必须为其所有成员添加前缀以避免命名冲突。

    ¥Because everything’s global, libraries must add a prefix to all their members to avoid naming collisions.

  • @extend 规则 也是全局的,这使得很难预测哪些样式规则将被扩展。

    ¥@extend rules are also global, which makes it difficult to predict which style rules will be extended.

  • 每个样式表都会在每次 @import 时执行并发出其 CSS,这会增加编译时间并产生臃肿的输出。

    ¥Each stylesheet is executed and its CSS emitted every time it’s @imported, which increases compilation time and produces bloated output.

  • 无法定义下游样式表无法访问的私有成员或占位符选择器。

    ¥There was no way to define private members or placeholder selectors that were inaccessible to downstream stylesheets.

新的模块系统和 @use 规则解决了所有这些问题。

¥The new module system and the @use rule address all these problems.

How Do I Migrate?

我们编写了一个 迁移工具,它可以自动将大多数基于 @import 的代码瞬间转换为基于 @use 的代码。只需将其指向你的入口点并让它运行!

¥We’ve written a migration tool that automatically converts most @import-based code to @use-based code in a flash. Just point it at your entrypoints and let it run!

SCSS Syntax

// foundation/_code.scss
code {
  padding: .25em;
  line-height: 0;
}
// foundation/_lists.scss
ul, ol {
  text-align: left;

  & & {
    padding: {
      bottom: 0;
      left: 0;
    }
  }
}
// style.scss
@import 'foundation/code', 'foundation/lists';

Sass Syntax

// foundation/_code.sass
code
  padding: .25em
  line-height: 0

// foundation/_lists.sass
ul, ol
  text-align: left

  & &
    padding:
      bottom: 0
      left: 0



// style.sass
@import foundation/code, foundation/lists

CSS Output

code {
  padding: .25em;
  line-height: 0;
}

ul, ol {
  text-align: left;
}
ul ul, ol ol {
  padding-bottom: 0;
  padding-left: 0;
}










当 Sass 导入一个文件时,该文件会被评估,就好像它的内容直接出现在 @import 的位置一样。导入文件中的任何 混入函数变量 都可用,并且其所有 CSS 都包含在写入 @import 的确切位置。此外,在 @import 之前定义的任何 mixins、函数或变量(包括来自其他 @import 的)都可以在导入的样式表中使用。

¥When Sass imports a file, that file is evaluated as though its contents appeared directly in place of the @import. Any mixins, functions, and variables from the imported file are made available, and all its CSS is included at the exact point where the @import was written. What’s more, any mixins, functions, or variables that were defined before the @import (including from other @imports) are available in the imported stylesheet.

⚠️ Heads up!

如果同一样式表被导入多次,则每次都会重新评估。如果它只定义函数和 mixins,这通常没什么大不了的,但如果它包含样式规则,它们将被多次编译为 CSS

¥If the same stylesheet is imported more than once, it will be evaluated again each time. If it just defines functions and mixins, this usually isn’t a big deal, but if it contains style rules they’ll be compiled to CSS more than once.

查找文件查找文件 permalink

¥Finding the File

为导入的每个样式表写出绝对 URL 没有任何乐趣,因此 Sass 查找要导入的文件的算法使它变得更容易一些。对于初学者来说,你不必明确写出要导入的文件的扩展名;@import "variables" 将自动加载 variables.scssvariables.sassvariables.css

¥It wouldn’t be any fun to write out absolute URLs for every stylesheet you import, so Sass’s algorithm for finding a file to import makes it a little easier. For starters, you don’t have to explicitly write out the extension of the file you want to import; @import "variables" will automatically load variables.scss, variables.sass, or variables.css.

⚠️ Heads up!

为了确保样式表适用于每个操作系统,Sass 通过 URL 而不是文件路径导入文件。这意味着你需要使用正斜杠,而不是反斜杠,即使你在 Windows 上也是如此。

¥To ensure that stylesheets work on every operating system, Sass imports files by URL, not by file path. This means you need to use forward slashes, not backslashes, even when you’re on Windows.

加载路径加载路径 permalink

¥Load Paths

所有 Sass 实现都允许用户提供加载路径:Sass 在解析导入时将查找的文件系统上的路径。例如,如果传递 node_modules/susy/sass 作为加载路径,则可以使用 @import "susy" 来加载 node_modules/susy/sass/susy.scss

¥All Sass implementations allow users to provide load paths: paths on the filesystem that Sass will look in when resolving imports. For example, if you pass node_modules/susy/sass as a load path, you can use @import "susy" to load node_modules/susy/sass/susy.scss.

不过,导入始终首先相对于当前文件进行解析。仅当不存在与导入匹配的相对文件时才会使用加载路径。这可以确保你在添加新库时不会意外地弄乱相关导入。

¥Imports will always be resolved relative to the current file first, though. Load paths will only be used if no relative file exists that matches the import. This ensures that you can’t accidentally mess up your relative imports when you add a new library.

💡 Fun fact:

与其他一些语言不同,Sass 不要求你使用 ./ 进行相对导入。相对导入始终可用。

¥Unlike some other languages, Sass doesn’t require that you use ./ for relative imports. Relative imports are always available.

局部局部 permalink

¥Partials

按照惯例,仅用于导入而不是自行编译的 Sass 文件以 _ 开头(如 _code.scss 所示)。这些称为部分文件,它们告诉 Sass 工具不要尝试自行编译这些文件。导入部分时可以省略 _

¥As a convention, Sass files that are only meant to be imported, not compiled on their own, begin with _ (as in _code.scss). These are called partials, and they tell Sass tools not to try to compile those files on their own. You can leave off the _ when importing a partial.

索引文件索引文件 permalink

¥Index Files

兼容性:
Dart Sass
LibSass
since 3.6.0
Ruby Sass
since 3.6.0

如果你在文件夹中写入 _index.scss_index.sass,则导入文件夹本身时,该文件将加载到其位置。

¥If you write an _index.scss or _index.sass in a folder, when the folder itself is imported that file will be loaded in its place.

SCSS Syntax

// foundation/_code.scss
code {
  padding: .25em;
  line-height: 0;
}
// foundation/_lists.scss
ul, ol {
  text-align: left;

  & & {
    padding: {
      bottom: 0;
      left: 0;
    }
  }
}
// foundation/_index.scss
@import 'code', 'lists';
// style.scss
@import 'foundation';

Sass Syntax

// foundation/_code.sass
code
  padding: .25em
  line-height: 0

// foundation/_lists.sass
ul, ol
  text-align: left

  & &
    padding:
      bottom: 0
      left: 0



// foundation/_index.sass
@import code, lists
// style.sass
@import foundation

CSS Output

code {
  padding: .25em;
  line-height: 0;
}

ul, ol {
  text-align: left;
}
ul ul, ol ol {
  padding-bottom: 0;
  padding-left: 0;
}














定制导入器定制导入器 permalink

¥Custom Importers

所有 Sass 实现都提供了一种定义自定义导入器的方法,它控制 @import 定位样式表的方式:

¥All Sass implementations provide a way to define custom importers, which control how @imports locate stylesheets:

嵌套嵌套 permalink

¥Nesting

导入通常写在样式表的顶层,但并非必须如此。它们也可以嵌套在 样式规则CSS at 规则 内。导入的 CSS 嵌套在该上下文中,这使得嵌套导入对于将 CSS 块的范围限定到特定元素或媒体查询非常有用。嵌套导入中定义的顶层 混入函数变量 仅在嵌套上下文中可用。

¥Imports are usually written at the top level of a stylesheet, but they don’t have to be. They can nested within style rules or plain CSS at-rules as well. The imported CSS is nested in that context, which makes nested imports useful for scoping a chunk of CSS to a particular element or media query. Top-level mixins, functions, and variables defined in the nested import are only available in the nested context.

SCSS Syntax

// _theme.scss
pre, code {
  font-family: 'Source Code Pro', Helvetica, Arial;
  border-radius: 4px;
}
// style.scss
.theme-sample {
  @import "theme";
}

Sass Syntax

// _theme.sass
pre, code
  font-family: 'Source Code Pro', Helvetica, Arial
  border-radius: 4px

// style.sass
.theme-sample
  @import theme

CSS Output

.theme-sample pre, .theme-sample code {
  font-family: 'Source Code Pro', Helvetica, Arial;
  border-radius: 4px;
}







💡 Fun fact:

嵌套导入对于确定第三方样式表的范围非常有用,但如果你是要导入的样式表的作者,那么通常更好的主意是在 混合 中编写样式并将该 mixin 包含在嵌套上下文中。mixin 可以以更灵活的方式使用,并且在查看导入的样式表时更清楚它的用途。

¥Nested imports are very useful for scoping third-party stylesheets, but if you’re the author of the stylesheet you’re importing, it’s usually a better idea to write your styles in a mixin and include that mixin in the nested context. A mixin can be used in more flexible ways, and it’s clearer when looking at the imported stylesheet how it’s intended to be used.

⚠️ Heads up!

嵌套导入中的 CSS 被评估为 mixin,这意味着任何 父选择器 将引用样式表嵌套在其中的选择器。

¥The CSS in nested imports is evaluated like a mixin, which means that any parent selectors will refer to the selector in which the stylesheet is nested.

SCSS Syntax

// _theme.scss
ul li {
  $padding: 16px;
  padding-left: $padding;
  [dir=rtl] & {
    padding: {
      left: 0;
      right: $padding;
    }
  }
}
// style.scss
.theme-sample {
  @import "theme";
}

Sass Syntax

// _theme.sass
ul li
  $padding: 16px
  padding-left: $padding
  [dir=rtl] &
    padding:
      left: 0
      right: $padding



// style.sass
.theme-sample
  @import theme

CSS Output

.theme-sample ul li {
  padding-left: 16px;
}
[dir=rtl] .theme-sample ul li {
  padding-left: 0;
  padding-right: 16px;
}










导入 CSS导入 CSS permalink

¥Importing CSS

兼容性:
Dart Sass
since 1.11.0
LibSass
partial
Ruby Sass

LibSass 支持导入扩展名为 .css 的文件,但与规范相反,它们被视为 SCSS 文件,而不是被解析为 CSS。此行为已被弃用,并且正在进行更新以支持下述行为。

¥LibSass supports importing files with the extension .css, but contrary to the specification they’re treated as SCSS files rather than being parsed as CSS. This behavior has been deprecated, and an update is in the works to support the behavior described below.

除了导入 .sass.scss 文件之外,Sass 还可以导入普通的旧 .css 文件。唯一的规则是导入不得显式包含 .css 扩展名,因为它用于指示 CSS @import

¥In addition to importing .sass and .scss files, Sass can import plain old .css files. The only rule is that the import must not explicitly include the .css extension, because that’s used to indicate a plain CSS @import.

SCSS Syntax

// code.css
code {
  padding: .25em;
  line-height: 0;
}
// style.scss
@import 'code';

Sass Syntax

// code.css
code {
  padding: .25em;
  line-height: 0;
}
// style.sass
@import code

CSS Output

code {
  padding: .25em;
  line-height: 0;
}





Sass 导入的 CSS 文件不允许任何特殊的 Sass 功能。为了确保作者不会意外地在 CSS 中写入 Sass,所有不是有效 CSS 的 Sass 功能都会产生错误。否则,CSS 将按原样渲染。甚至可以是 扩展

¥CSS files imported by Sass don’t allow any special Sass features. In order to make sure authors don’t accidentally write Sass in their CSS, all Sass features that aren’t also valid CSS will produce errors. Otherwise, the CSS will be rendered as-is. It can even be extended!

CSS @importCSS @import permalink

¥Plain CSS @imports

兼容性:
Dart Sass
LibSass
partial
Ruby Sass

默认情况下,LibSass 正确处理纯 CSS 导入。但是,任何 定制导入商 都会错误地应用于纯 CSS @import 规则,从而使这些规则可以加载 Sass 文件。

¥By default, LibSass handles plain CSS imports correctly. However, any custom importers will incorrectly apply to plain-CSS @import rules, making it possible for those rules to load Sass files.

因为 @import 也在 CSS 中定义,所以 Sass 需要一种编译纯 CSS @import 的方法,而无需在编译时尝试导入文件。为了实现这一点,并确保 SCSS 尽可能成为 CSS 的超集,Sass 会将具有以下特性的任何 @import 编译为纯 CSS 导入:

¥Because @import is also defined in CSS, Sass needs a way of compiling plain CSS @imports without trying to import the files at compile time. To accomplish this, and to ensure SCSS is as much of a superset of CSS as possible, Sass will compile any @imports with the following characteristics to plain CSS imports:

  • 导入 URL.css 结尾的位置。

    ¥Imports where the URL ends with .css.

  • 导入 URLhttp://https:// 开头的位置。

    ¥Imports where the URL begins http:// or https://.

  • URL 写为 url() 的导入。

    ¥Imports where the URL is written as a url().

  • 具有媒体查询的导入。

    ¥Imports that have media queries.

SCSS Syntax

@import "theme.css";
@import "http://fonts.googleapis.com/css?family=Droid+Sans";
@import url(theme);
@import "landscape" screen and (orientation: landscape);

Sass Syntax

@import "theme.css"
@import "http://fonts.googleapis.com/css?family=Droid+Sans"
@import url(theme)
@import "landscape" screen and (orientation: landscape)

CSS Output

@import "theme.css";
@import "http://fonts.googleapis.com/css?family=Droid+Sans";
@import url(theme);
@import "landscape" screen and (orientation: landscape);

插值插值 permalink

¥Interpolation

尽管 Sass 导入不能使用 插值法(以确保始终可以分辨 混入函数变量 来自何处),但纯 CSS 导入可以。这使得动态生成导入成为可能,例如基于 mixin 参数。

¥Although Sass imports can’t use interpolation (to make sure it’s always possible to tell where mixins, functions, and variables come from), plain CSS imports can. This makes it possible to dynamically generate imports, for example based on mixin parameters.

SCSS Syntax

@mixin google-font($family) {
  @import url("http://fonts.googleapis.com/css?family=#{$family}");
}

@include google-font("Droid Sans");

Sass Syntax

@mixin google-font($family)
  @import url("http://fonts.googleapis.com/css?family=#{$family}")


@include google-font("Droid Sans")

CSS Output

@import url("http://fonts.googleapis.com/css?family=Droid Sans");




导入和模块导入和模块 permalink

¥Import and Modules

兼容性:
Dart Sass
since 1.23.0
LibSass
Ruby Sass

Only Dart Sass currently supports @use. Users of other implementations must use the @import rule instead.

Sass 的 模块系统@import 无缝集成,无论你是导入包含 @use 规则的文件还是加载包含作为模块导入的文件。我们希望尽可能顺利地从 @import@use 的过渡。

¥Sass’s module system integrates seamlessly with @import, whether you’re importing a file that contains @use rules or loading a file that contains imports as a module. We want to make the transition from @import to @use as smooth as possible.

导入模块系统文件导入模块系统文件 permalink

¥Importing a Module-System File

当你导入包含 @use 规则的文件时,导入文件可以访问直接在该文件中定义的所有成员(甚至私有成员),但不能访问该文件已加载的模块中的任何成员。但是,如果该文件包含 @forward 规则,则导入文件将有权访问转发的成员。这意味着你可以导入为与模块系统一起使用而编写的库。

¥When you import a file that contains @use rules, the importing file has access to all members (even private members) defined directly in that file, but not any members from modules that file has loaded. However, if that file contains @forward rules, the importing file will have access to forwarded members. This means that you can import a library that was written to be used with the module system.

⚠️ Heads up!

当导入具有 @use 规则的文件时,由这些规则传递加载的所有 CSS 都会包含在生成的样式表中,即使它已被另一个导入包含。如果你不小心,这可能会导致 CSS 输出臃肿!

¥When a file with @use rules is imported, all the CSS transitively loaded by those is included in the resulting stylesheet, even if it’s already been included by another import. If you’re not careful, this can result in bloated CSS output!

仅导入文件仅导入文件 permalink

¥Import-Only Files

@use 有意义的 API 可能对 @import 没有意义。例如,@use 默认为所有成员添加命名空间,因此你可以安全地使用短名称,但 @import 不会,因此你可能需要更长的名称。如果你是库作者,你可能会担心如果你更新库以使用新的模块系统,你现有的基于 @import 的用户将会崩溃。

¥An API that makes sense for @use might not make sense for @import. For example, @use adds a namespace to all members by default so you can safely use short names, but @import doesn’t so you might need something longer. If you’re a library author, you may be concerned that if you update your library to use the new module system, your existing @import-based users will break.

为了使这更容易,Sass 还支持仅导入文件。如果你将文件命名为 <name>.import.scss,则只会在导入时加载该文件,而不会为 @use 加载该文件。这样,你可以保留 @import 用户的兼容性,同时仍然为新模块系统的用户提供良好的 API

¥To make this easier, Sass also supports import-only files. If you name a file <name>.import.scss, it will only be loaded for imports, not for @uses. This way, you can retain compatibility for @import users while still providing a nice API for users of the new module system.

SCSS Syntax

// _reset.scss

// Module system users write `@include reset.list()`.
@mixin list() {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }
}
// _reset.import.scss

// Legacy import users can keep writing `@include reset-list()`.
@forward "reset" as reset-*;

Sass Syntax

// _reset.sass

// Module system users write `@include reset.list()`.
@mixin list()
  ul
    margin: 0
    padding: 0
    list-style: none


// _reset.import.sass

// Legacy import users can keep writing `@include reset-list()`.
@forward "reset" as reset-*

通过导入配置模块通过导入配置模块 permalink

¥Configuring Modules Through Imports

兼容性:
Dart Sass
since 1.24.0
LibSass
Ruby Sass

你可以通过在首先加载该模块的 @import 之前定义全局变量来通过 @import 加载 配置模块

¥You can configure modules that are loaded through an @import by defining global variables prior the @import that first loads that module.

SCSS Syntax

// _library.scss
$color: blue !default;

a {
  color: $color;
}
// _library.import.scss
@forward 'library' as lib-*;
// style.sass
$lib-color: green;
@import "library";

Sass Syntax

$color: blue !default

a
  color: $color


// _library.import.sass
@forward 'library' as lib-*
// style.sass
$lib-color: green
@import "library"

CSS Output

a {
  color: green;
}












⚠️ Heads up!

模块仅加载一次,因此,如果你在第一次 @import 模块后更改配置(即使是间接的),则在再次 @import 模块时,更改将被忽略。

¥Modules are only loaded once, so if you change the configuration after you @import a module for the first time (even indirectly), the change will be ignored if you @import the module again.

加载包含导入的模块加载包含导入的模块 permalink

¥Loading a Module That Contains Imports

当你使用 @use(或 @forward)加载使用 @import 的模块时,该模块将包含你加载的样式表定义的所有公共成员以及样式表传递导入的所有内容。换句话说,导入的所有内容都被视为是在一个大样式表中编写的。

¥When you use @use (or @forward) load a module that uses @import, that module will contain all the public members defined by the stylesheet you load and everything that stylesheet transitively imports. In other words, everything that’s imported is treated as though it were written in one big stylesheet.

这使得即使在你依赖的所有库都转换为新的模块系统之前,也可以轻松地在样式表中使用 @use 开始转换。但请注意,如果他们确实进行转换,他们的 API 很可能会发生变化!

¥This makes it easy to convert start using @use in a stylesheet even before all the libraries you depend on have converted to the new module system. Be aware, though, that if they do convert their APIs may well change!