提示

  官方文档:At-Rules (opens new window)

  先提前展示一下后面要用到的样式目录:

styles/
|-- _index.scss
|-- variables/
|   |-- _colors.scss
|   |-- _typography.scss
|-- components/
|   |-- _buttons.scss
|   |-- _forms.scss
|-- main.scss

# 一、@use

  你可以简单的将@use 看作是对@import 的升级。

  @use 加载的样式表被称为“模块”,多次引入只包含一次(即:每一个@use 相对独立)。

提示

  现在官网更加推荐使用 具有命名空间功能 的 @use (opens new window) 代替 @import (opens new window)

# 1、代码示例

  下面简单的看一下@use 的使用方式:

通过下面的案例,可以看到@use 相较于@import 的优势:模块化划分

@use 'src/_global';
// @use 'src/_global2' as g2;

body {
  font-size: global.$font-size; // 使用 $ 变量
  width: global.column-width(3, 12); // 使用@function函数
  @include global.bgColor(#f00); // 使用@mixin混入
}

// h2 {
//   // 使用命名空间
//   @include g2.bgColor(#f00);
// }

# 2、私有变量

  如果我们处于某种考虑,我们并不想暴露_global.scss 文件中中的某些 scss 变量时,我们可以使用$-

提示

  当然我们也可以通过后面的 @forward 控制哪些需要暴露

@use 'src/corners';

.button {
  @include corners.rounded; // 可以正常使用

  padding: 5px + corners.$-radius; // 报错 ✖
}

# 3、可配置变量 ✨

  scss 的强大之一就是其 css 的可控性(使用 with),如下:

@use 'library' with (
  $black: #222
);

# 4、变量重分配

  在只有父子关系时,父是可以直接调用子中的变量的,但跨域三代就不能直接使用了,需要对变量进行重分配:

@use 'override';

// 使用 library 中的变量
@debug library.$color; //=> blue

# 二、@forward

  上面的变量重分配方式显然不是长久之策,如果要跨代分配/共享更多的变量怎么办,这还没有算上样式、 Mixin 等

提示

  我们可以将@forward,看成类似于 es6 中的 export,进行模块成员进行导出。

  其中,@use@forward的区别如下:

  • @use 用于引入模块,提供更严格的命名空间和作用域控制
  • @forward 用于将样式、变量、Mixin 等从一个模块导出,以便其他模块可以使用

# 1、模块导出

  对与@forward 的使用,我们有如下使用方式:

@use 'index' as *;

.app-button {
  @include btn-button-style; // 使用导出的Mixin
}

# 2、可配置变量 ✨

@use 'opinionated' with (
  $black: #333
);

# 3、控制可见性

  • _bootstrap.scss
// 1、指定转发哪些
@forward 'users/common' show $font-size;

// 2、指定不转发哪些
@forward 'users/common' hide bgColor;

# 4、添加前缀

  • _bootstrap.scss
// 转发时,为不同文件内样式的使用声明一个前缀
@forward 'users/common' as c-*;
@forward 'users/global' as g-* hide g-font-size; // 要想使hide、show作用生效,也要加前缀(向外生效🤔)
  • user.scss
@use './bootstrap';

.container {
  font-size: bootstrap.$c-font-size;
  width: bootstrap.c-column-width(3, 12);
  @include bootstrap.g-base(#f00);
}

# 三、@at-root

  @at-root 可以使被嵌套的选择器或属性跳出嵌套。

思考:为什么要跳出嵌套?

可以增加它的作用范围、针对于有待移动需求的元素

# 1、应用示例

  场景的应用场景就是 CSS 与 BEM 命名规范。

.block {
  width: 1000px;
  @at-root #{&}__element {
    font-size: 12px;
    @at-root #{&}--modifier {
      font-size: 16px;
    }
  }

  @at-root #{&}--modifier {
    font-size: 14px;
  }
}

# 2、限制条件

  默认@at-root 只会跳出选择器嵌套,而不能跳出@media 或@supports,如果要跳出这两种,则需要使用@at-root(without: media)@at-root(without: supports)

  其中,这种语法的关键词有四个:

  • all(表示所有)
  • rule(常规 css):默认选项
  • media
  • supports
更新于 : 7/10/2025, 1:15:39 AM