如何校验自定义元素的 :host 样式必须提供默认回退?

解读

国内前端团队在做 Web Components 项目时,常把 :host 当作“根节点”来写主题变量,例如 :host { --theme-color: #1890ff; }。
一旦组件被放进旧版浏览器(如国内仍要兼容的 Chrome 58、360 安全浏览器 10)或关闭 Custom Elements 支持的运行时,整条规则会被忽略,导致页面白屏或样式错位。
因此,面试官想知道:

  1. 你是否意识到“无回退”属于可访问性与向下兼容缺陷;
  2. 能否用 Stylelint 把这条隐形规范自动化,而不是靠 code review 口头提醒;
  3. 对 PostCSS 抽象语法树(AST)与 Stylelint 插件机制是否熟悉,能否给出“可落地”的代码,而非泛泛而谈“写个插件”。

知识点

  1. Stylelint 插件体系:
    • stylelint.createPlugin(ruleName, function(primaryOption, secondaryOption, context) {})
    • 通过 postcss.parse 得到的 Root 节点遍历 Rule 选择器,用 postcss-selector-parser 把 :host 解析成伪类节点。
  2. 回退判定策略:
    • 强规范:同一 Rule 节点内必须出现与自定义属性同名的标准属性,如 color: #000; color: var(--theme-color);。
    • 弱规范:至少出现一条不含 var() 的属性,或上级已有全局回退。
    • 本题采用“强规范”示例,方便 CI 直接拦截合并请求。
  3. 自动修复(context.fix):
    • 把 var() 行复制一份放到前面,并去掉 var() 函数,实现“一键补回退”。
  4. 国内工程链集成:
    • 规则包发布到私有 npm,在 .stylelintrc.js 里 extends: ['@company/stylelint-config-webc'];
    • GitHub Actions / GitLab CI 里跑 stylelint 'src/**/*.css' --max-warnings 0,阻断 MR。

答案

  1. 初始化插件文件 stylelint-plugin-host-fallback/index.js:
const stylelint = require('stylelint');
const selectorParser = require('postcss-selector-parser');
const { utils } = stylelint;

const ruleName = 'plugin/host-fallback';
const messages = utils.ruleMessages(ruleName, {
  expected: (prop) => `自定义属性 "${prop}" 在 :host 中必须提供标准回退`,
});

module.exports = stylelint.createPlugin(ruleName, function(primary, _, context) {
  return (root, result) => {
    root.walkRules(rule => {
      let hasHost = false;
      selectorParser(selectors => {
        selectors.walkPseudos(p => {
          if (p.value === ':host') hasHost = true;
        });
      }).processSync(rule.selector);

      if (!hasHost) return;

      const customProps = new Set();
      const standardProps = new Set();

      rule.walkDecls(decl => {
        if (decl.value.includes('var(')) {
          const match = decl.value.match(/var\(--([^,)]+)/);
          if (match) customProps.add(`--${match[1]}`);
        } else {
          standardProps.add(decl.prop);
        }
      });

      customProps.forEach(cp => {
        if (!standardProps.has(cp)) {
          if (context.fix) {
            // 自动修复:把 var() 行复制一份,去掉 var() 作为回退
            rule.prepend({
              prop: cp,
              value: rule.nodes.find(n => n.value.includes(cp)).value.replace(/var\(--[^)]+\)/, '#000').split(',')[0],
            });
          } else {
            utils.report({
              message: messages.expected(cp),
              node: rule,
              result,
              ruleName,
            });
          }
        }
      });
    });
  };
});
  1. 在 .stylelintrc.js 中启用:
module.exports = {
  plugins: ['./stylelint-plugin-host-fallback'],
  rules: {
    'plugin/host-fallback': true,
  },
};
  1. 运行 npx stylelint src/**/*.css 即可拦截如下代码:
:host {
  --theme-color: var(--theme-color); /* 报错:无回退 */
}

并提示:
“自定义属性 "--theme-color" 在 :host 中必须提供标准回退”

  1. 若加 --fix,插件会自动补全:
:host {
  --theme-color: #000;
  --theme-color: var(--theme-color);
}

拓展思考

  1. 如果团队允许“全局回退文件”机制,可把规则升级为“查找祖先节点是否已声明同名标准属性”,降低误报。
  2. 对 Shadow DOM 的 ::slotted() 选择器同样存在回退缺失问题,可复用上述 AST 思路再写一条 plugin/slotted-fallback 规则,形成“Web Components 样式质量门禁”套装。
  3. 在 Monorepo 场景下,可把插件做成 eslint-style 共享配置,结合 changeset 发版,保证所有业务线一键升级,避免“各写各的插件”造成规则漂移。