如何提示将 :host 样式限制在组件内部文件?

解读

国内前端团队普遍采用“单文件组件”或“CSS-in-JS”模式,:host 伪类只在 Shadow DOM 或 Vue Scoped、Angular ViewEncapsulation 场景下生效。一旦 :host 被写到全局样式文件,轻则样式污染,重则覆盖组件库主题变量,属于高危“跨边界”代码。Stylelint 作为门禁工具,必须在编译前就把这类“越界”代码拦截下来,并给出可修复的提示,而不是等到运行时才发现。因此,面试官想考察的是“能否用 Stylelint 的语义分析能力,把‘只能在组件内出现的语法’和‘只能在全局出现的语法’做强制隔离”。

知识点

  1. PostCSS 抽象语法树(AST)节点类型:Rule.selector 中包含伪类选择器时,其值会被解析为 :host 或 :host(...)
  2. Stylelint 插件开发三件套:
    • ruleName 必须带命名空间,如 corp/selector-host-allowed-files
    • root.walkRules 遍历所有 Rule 节点
    • utils.report 上报错误,支持 message 与 node 定位
  3. 文件路径判定:
    • 通过 root.source.input.file 拿到绝对路径
    • 用 minimatch 或 micromatch 匹配“组件内部”特征,如 **/components/**/*.vue、*.scoped.less、*[_.]scoped.*
  4. 自动修复:
    • 在 utils.report 里返回 fix() 函数,把 :host 替换成 :root 或注释掉,或直接删除整行,视团队规范而定
  5. 与 GitLab-CI / GitHub Actions 集成:
    • 在 MR 阶段运行 stylelint --custom-syntax postcss-html
    • 配合 stylelint-codequality 输出 GitLab Code Quality JSON,MR 页面直接标红
  6. 国内常见坑:
    • Windows 路径分隔符需 path.posix.normalize 统一
    • 微前端场景下,子应用可能把组件放在 /packages/**/src 里,需要允许可配置白名单

答案

实现一条自定义规则 plugin/selector-host-allowed-files,核心代码如下(可直接放进 .stylelintrc.js 的 plugins 字段):

// stylelint-plugin-host-limiter.js
const stylelint = require('stylelint');
const { minimatch } = require('minimatch');

const ruleName = 'plugin/selector-host-allowed-files';
const messages = stylelint.utils.ruleMessages(ruleName, {
  rejected: '`:host` is not allowed in global styles; move it into a component file (e.g. *.scoped.less, *.vue)'
});

module.exports = stylelint.createPlugin(ruleName, (primaryOption, secondaryOption = {}) => {
  return (root, result) => {
    const file = root.source?.input?.file;
    if (!file) return;

    // 默认只让 *.scoped.* 和 *.vue 里能用 :host
    const componentPatterns = secondaryOption.allowPatterns || ['**/*.scoped.*', '**/*.vue'];
    const isComponentFile = componentPatterns.some(p => minimatch(file, p));

    root.walkRules(rule => {
      if (!rule.selector.includes(':host')) return;
      if (isComponentFile) return;

      stylelint.utils.report({
        message: messages.rejected,
        node: rule,
        result,
        ruleName,
        line: rule.source?.start?.line,
        column: rule.source?.start?.column
      });
    });
  };
});

在 .stylelintrc.js 中启用:

module.exports = {
  plugins: ['./stylelint-plugin-host-limiter'],
  rules: {
    'plugin/selector-host-allowed-files': [true, {
      allowPatterns: ['**/*.scoped.less', '**/components/**/*.vue']
    }]
  }
};

运行 npx stylelint "**/*.{css,less,scss,vue}" 后,任何在 src/styles/theme.less 里写 :host { color: red; } 都会立即报错,并给出文件行号,CI 直接拦截合并请求。

拓展思考

  1. 如果团队使用 CSS Modules,可把 :host 限制在 *.module.css 文件;规则只需调整 allowPatterns 即可,无需改插件代码,体现“策略与实现分离”
  2. 对于 Stencil、Lit 等 Web Components 库,:host 有时需要写在 src/global/variables.css 做主题变量穿透,此时可在插件里再增加一个 denyPatterns 反向黑名单,允许在 src/global/variables.css 里出现 :host 但禁止其他全局文件
  3. 结合 stylelint --fix 能力,可自动把非法 :host 替换为带注释的 /* :host */,并输出警告,让开发者手动决定是迁移文件还是改选择器,实现“可修复但不静默破坏”
  4. 在大型中台项目里,可把该规则封装成公司级 npm 包 @corp/stylelint-config-host,并在 extends 中一键引入,保证所有微应用、子仓库用同一套“组件边界”策略,降低沟通成本