如何检测 ::slotted 选择器层级过深?

解读

面试官抛出这道题,核心想验证三件事:

  1. 你是否真的在 Web Components 场景里写过样式,知道 ::slotted 的“穿透”限制;
  2. 能否把“层级过深”这种主观描述量化成可计算的 AST 节点;
  3. 是否具备写自定义 Stylelint 规则的实战经验,而不是只会开关内置规则。
    在国内一线团队(阿里、腾讯、字节等)的代码评审里,Shadow DOM 样式滥用是性能红线,::slotted 套娃超过 3 层会直接打回,所以这道题既考理论也考落地。

知识点

  1. ::slotted 语法特性

    • 只能写在 Shadow DOM 内的 <style> 里;
    • 其后代选择器最多只能再写一层,浏览器会忽略更深层的写法;
    • 写得太深往往意味着组件封装失败,把业务逻辑泄露到 Shadow DOM 外。
  2. PostCSS 选择器解析

    • 使用 postcss-selector-parser 把选择器拆成节点树;
    • tag 类型且 value === '::slotted' 的节点即为命中点;
    • 从该节点往右统计 descendant(空格)或 child(>)数量即可得到“深度”。
  3. Stylelint 自定义规则骨架

    • 规则名必须带命名空间,如 plugin/selector-slotted-max-depth;
    • 通过 root.walkRules 遍历所有规则;
    • 用 utils.report 上报错误,同时提供 fix 回调可自动删除多余层级。
  4. 量化阈值

    • 国内团队普遍把阈值设为 2(即 ::slotted() 本身算 0,后面最多再写 1 层);
    • 需要做成可配置,默认 2,方便不同项目自行调整。

答案

下面给出完整可落地的自定义规则代码,可直接放到项目根目录 stylelint-plugins/selector-slotted-max-depth.js,并在 .stylelintrc.js 里引用。

// stylelint-plugins/selector-slotted-max-depth.js
const stylelint = require('stylelint');
const parser = require('postcss-selector-parser');
const { utils } = stylelint;

const ruleName = 'plugin/selector-slotted-max-depth';
const messages = utils.ruleMessages(ruleName, {
  expected: (depth, max) =>
    `Expected ::slotted() depth <= ${max}, but found ${depth}`,
});

const meta = {
  url: null,
  fixable: true, // 标记可自动修复
};

function plugin(maxDepth = 2) {
  return (root, result) => {
    const validOptions = utils.validateOptions(result, ruleName, {
      actual: maxDepth,
      possible: [Number],
    });
    if (!validOptions) return;

    root.walkRules(rule => {
      // 只检查 Shadow DOM 内的样式
      if (!rule.selector.includes('::slotted')) return;

      parser(selectors => {
        selectors.walkTags(tag => {
          if (tag.value !== '::slotted') return;

          // 计算 ::slotted 右侧深度
          let depth = 0;
          let next = tag.parent;
          while (next) {
            if (next.type === 'selector') {
              // 遇到逗号分隔的下一个选择器就停止
              break;
            }
            if (next.type === 'descendant' || next.type === 'child') {
              depth++;
            }
            next = next.parent;
          }

          if (depth > maxDepth) {
            utils.report({
              message: messages.expected(depth, maxDepth),
              node: rule,
              result,
              ruleName,
              index: rule.toString().indexOf(rule.selector),
              fix(fixer) {
                // 简单修复:直接截断多余层级
                const tokens = rule.selector.split('::slotted');
                const head = tokens[0] + '::slotted';
                const tail = tokens[1];
                const newTail = tail
                  .split(/[\s>]+/)
                  .slice(0, maxDepth + 1)
                  .join(' ');
                return fixer.replaceText(rule, head + newTail);
              },
            });
          }
        });
      }).processSync(rule.selector);
    });
  };
}

plugin.ruleName = ruleName;
plugin.messages = messages;
plugin.meta = meta;
module.exports = stylelint.createPlugin(ruleName, plugin);

配置示例:

// .stylelintrc.js
module.exports = {
  plugins: ['./stylelint-plugins/selector-slotted-max-depth'],
  rules: {
    'plugin/selector-slotted-max-depth': [2, { severity: 'error' }],
  },
};

运行 npx stylelint "**/*.css" 即可检测,加 --fix 可自动截断多余层级。

拓展思考

  1. 性能角度
    浏览器对 ::slotted 的匹配是 O(n²) 级别,层级越深,组件实例越多,重排代价越大。把阈值做成 CI 门禁,可在合并请求阶段就拦截性能隐患。

  2. 与 Vue/React 单文件组件结合
    国内项目 90% 用 Vue,<style scoped> 会被编译成 Shadow DOM 模式。把上述规则封装成 stylelint-config-xxx 包,在集团内部 Nexus 私服发布,各业务线一键继承即可。

  3. 更精细的检测
    可以扩展规则,区分 ::slotted(*) 与 ::slotted(div.foo),对通配选择器再降一层阈值,因为通配在 Shadow DOM 内会强制遍历所有分发节点,危害更大。

  4. 与 Design Token 联动
    如果团队使用 Token 体系,可进一步检查 ::slotted 内是否出现硬编码颜色、字号,把“深度”与“违规声明”两条规则合并成一条复合规则,一次扫描输出双重报告,减少 CI 时间。