如何检测子应用使用了全局 --app- 前缀变量?

解读

在微前端或大型多仓库前端架构里,主应用会把设计令牌(Design Tokens)以 --app-* 形式注入到 :root,供所有子应用消费。子应用如果“手滑”自己再声明一份同前缀变量,就会污染全局命名空间,造成样式回退、优先级混乱甚至线上事故。面试官想知道你能否用 Stylelint 把这类“越权声明”自动拦截在 CI 阶段,而不是靠 code review 肉眼排查。

知识点

  1. Stylelint 规则体系:内置规则只能覆盖标准 CSS 语法,检测自定义属性前缀必须写插件。
  2. PostCSS AST:自定义属性在 AST 里类型是 decl,prop 字段以双连字符开头。
  3. 插件编写范式:
    • 暴露一个规则函数,返回 (root, result) => {}
    • 用 root.walkDecls(/^--/, …) 遍历所有自定义属性声明
    • 判断 decl.prop.startsWith('--app-') 且父节点不是主应用允许的白名单(如 :root, .theme-light)
    • 调用 utils.report({ message, node: decl, result, ruleName }) 上报错误
  4. 自动修复:在 decl.prop 前插入子应用命名空间,如把 --app-radius 改成 --subA-radius,并返回 fix() 函数。
  5. 国内工程化配套:
    • 把插件发到公司私有 npm 源,统一在 @company/stylelint-config-micro 里默认开启
    • 在 GitLab-CI / GitHub Actions 里跑 stylelint "**/*.{css,scss,less}" --max-warnings 0,失败即阻断合并
    • VS Code 插件 stylelint 自动读取项目配置,保存即提示,降低本地调试成本

答案

  1. 创建插件文件 stylelint-plugin-global-prefix/index.js
const stylelint = require('stylelint');
const { namespace } = require('stylelint/lib/utils');
const ruleName = namespace('global-prefix', 'micro-frontend');
const messages = stylelint.utils.ruleMessages(ruleName, {
  rejected: (unwanted) => `子应用禁止声明全局变量 "${unwanted}",请改用子应用私有前缀`
});
module.exports = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOption) {
  return function(root, result) {
    const validOptions = stylelint.utils.validateOptions(result, ruleName, {
      actual: primaryOption,
      possible: [true, false],
    });
    if (!validOptions || !primaryOption) return;
    const whitelist = (secondaryOption && secondaryOption.whitelistSelectors) || [':root'];
    root.walkDecls(/^--/, decl => {
      if (!decl.prop.startsWith('--app-')) return;
      const parentSelector = decl.parent && decl.parent.selector;
      const isAllowed = whitelist.some(s => parentSelector && parentSelector.includes(s));
      if (isAllowed) return;
      stylelint.utils.report({
        message: messages.rejected(decl.prop),
        node: decl,
        result,
        ruleName,
        word: decl.prop,
        fix() {
          // 简单示例:把 --app- 替换为 --subA-
          decl.prop = decl.prop.replace(/^--app-/, '--subA-');
        }
      });
    });
  };
});
  1. 在项目 .stylelintrc.js 中注册并开启
module.exports = {
  plugins: ['./stylelint-plugin-global-prefix'],
  rules: {
    'micro-frontend/global-prefix': [true, {
      whitelistSelectors: [':root', '.theme-light', '.theme-dark']
    }]
  }
};
  1. 运行 npx stylelint "src/**/*.{css,scss}"
    若子应用文件里出现:
.widget {
  --app-radius: 8px;
}

会立即报错:
✖ 子应用禁止声明全局变量 "--app-radius",请改用子应用私有前缀

  1. 加 --fix 可自动修正为 --subA-radius,CI 设置 --max-warnings 0 保证污染代码无法合入主干。

拓展思考

  1. 主应用动态注入:若主应用使用 @layer 或 CSS.registerProperty 做运行时注册,可把插件升级为扫描 JS/TS 文件里的 style.setProperty('--app-*', …),实现“双端”校验。
  2. 命名空间自动推导:结合 package.json 的 name 字段,把 --app- 自动替换为 --${pkgName}-,避免手工配置。
  3. 灰度与例外:在插件里支持 // stylelint-disable-next-line micro-frontend/global-prefix 注释,方便存量代码灰度迁移。
  4. 性能优化:对 Monorepo 里上万文件,先用 git diff --name-only 取变更集,再跑 Stylelint,节省 CI 时间。
  5. 与 Design Token 平台联动:把插件规则同步到内部设计令牌管理平台,一旦主应用新增 --app-* 变量,平台自动更新白名单,子应用无需手动改配置,实现“源头—检测—修复”闭环。