如何用 Sass 封装 `@scope`?

解读

@scope 是 CSS 原生即将落地的作用域隔离规则,允许开发者把一段样式限制在指定 DOM 子树内,避免全局污染。
国内面试场景下,面试官真正想考察的是:

  1. 你是否同步关注 CSS 新特性与Sass 的编译机制;
  2. 能否用 Sass 的宏能力(mixin / function / 占位符)把原生 @scope 包装成语义化、可复用、可传参的 API,同时保证向下兼容与编译安全;
  3. 是否理解**“封装”≠“简单包裹”,而是要做参数校验、作用域命名、回退方案、调试友好**等工程化细节。

知识点

  • @scope 语法结构:@scope (<root-selector>) to (<upper-bound>)? { ... }
  • Sass 的 @mixin 与 @content:利用 @content 把用户样式块注入到 @scope 内部
  • SassModule 系统:通过 @use 控制封装库对外暴露的 API,避免全局污染
  • 参数默认值与类型校验:meta.type-of() 做运行时校验,保证传入的 root 参数是字符串或列表
  • 编译时兼容:@supports 或 @if 判断浏览器是否支持 @scope,不支持时回退到命名空间类或属性选择器隔离
  • 源码映射与调试:在 mixin 内插入 @debug 输出实际编译后的选择器,方便 QA 定位

答案

  1. 建立 src/scope/_index.scss 文件,统一出口:
// src/scope/_index.scss
@use 'sass:string';
@use 'sass:meta';
@use 'sass:list';

/// 封装 @scope 的公共 mixin
/// @param {String|List} $root  作用域根选择器
/// @param {String|List|null} $upper  作用域上限(可选)
/// @content  用户样式块
@mixin scope($root, $upper: null) {
  // 1. 参数校验
  @if meta.type-of($root) != 'string' and meta.type-of($root) != 'list' {
    @error 'scope() 期望 $root 为字符串或列表,当前类型:#{meta.type-of($root)}';
  }

  // 2. 构造完整选择器
  $root-selector: if(meta.type-of($root) == 'list', list.join($root, (), $separator: comma), $root);
  $upper-selector: if($upper, $upper, '');

  // 3. 浏览器支持检测
  @supports at-rule(@scope) {
    @scope (#{$root-selector}) #{if($upper, 'to (#{$upper-selector})', '')} {
      @content;
    }
  } @else {
    // 4. 回退方案:BEM 式命名空间
    $ns: 'scope-' + string.slice(#{unique-id()}, 2, 7);
    @at-root {
      #{$root-selector} {
        @content;
      }
      // 给根节点打标记,方便 QA 识别
      @debug '[Sass-Scope] 回退模式,根节点:#{$root-selector}';
    }
  }
}
  1. 业务侧调用示例:
@use 'src/scope' as *;

.card {
  // 普通样式
  padding: 16px;

  // 作用域隔离
  @include scope('.card') {
    &__title { font-size: 18px; }
    &__body  { color: #666; }
  }
}

// 带上限的局部作用域
.sidebar {
  @include scope('.sidebar', '.content') {
    &-item { margin-bottom: 8px; }
  }
}
  1. 编译输出(浏览器支持 @scope 时):
@scope (.card) {
  .card__title { font-size: 18px; }
  .card__body  { color: #666; }
}

@scope (.sidebar) to (.content) {
  .sidebar-item { margin-bottom: 8px; }
}
  1. 若浏览器不支持,则回退为普通选择器,并通过 @debug 提示开发者当前处于降级模式,不阻塞上线。

拓展思考

  • 组件库场景:可把 scope() 与 theme() 结合,实现主题变量 + 样式隔离双保险,避免第三方业务样式穿透。
  • 微前端隔离:在 qiankun、wujie 等方案里,用 Sass 封装后的 @scope 生成带子应用前缀的局部样式,无需额外 ShadowDOM,减少运行时开销。
  • 自动化测试:在 Jest 或 Vitest 里写单元测试,断言编译产物是否包含 @scope,防止后续升级 Sass 版本导致新语法被误过滤。
  • 未来演进:当 @scope 成为 baseline 后,可移除回退逻辑,只保留 mixin 做“语义化网关”,一行配置即可关闭兼容模式,实现平滑下线。