如何检测多个组件重复构造相同样式表?

解读

在国内中大型前端团队里,UI 组件库往往由多人并行开发,「同一套视觉样式被不同组件反复 copy-paste」是代码审查中的高频痛点。面试官抛出此题,想验证候选人是否:

  1. 理解「重复样式」带来的包体积、可维护性、Design Token 一致性风险;
  2. 能把 Stylelint 的静态分析能力从「单行/单文件」规则延伸到「跨文件、跨组件」的重复检测;
  3. 熟悉国内落地场景:Monorepo + Webpack/Vite + CI 卡点 + 脚手架封装。

因此,答案必须给出「可落地的 Stylelint 技术方案」,而不是泛泛而谈「用肉眼 code review」。

知识点

  1. Stylelint 插件体系:自定义规则可访问 PostCSS AST,也能通过 stylelint.utils.report() 上报错误。
  2. PostCSS 的 OnceExit 钩子:在所有文件解析完成后统一聚合信息,适合做「跨文件」分析。
  3. 样式指纹:把声明块排序后做 JSON.stringify + stable-hash,可快速判断「结构级重复」。
  4. 国内 Monorepo 惯例:packages/ 下每个业务组件一个文件夹,插件需要支持 process.cwd() 与 rootPath 的灵活配置。
  5. CI 卡点:在 GitHub Actions / GitLab CI 中通过 stylelint --custom-syntax postcss-scss 'packages/**/*.scss' 触发检测,失败即阻断合并。
  6. 自动修复策略:给出 @import 'common/variations' 建议,或输出 JSON 报表供脚本统一抽离公共 class。

答案

实现思路分三步:「收集 → 指纹 → 报告」,全部用 Stylelint 插件完成,零额外 CLI。

第一步,创建自定义规则 stylelint-plugin-no-repeat-rules:

// plugins/no-repeat-rules.js
const { createHash } = require('crypto');
let cache = new Map(); // 指纹 -> 出现位置数组

module.exports = stylelint.createPlugin('plugin/no-repeat-rules', (primaryOption, secondaryOption = {}) => {
  const { threshold = 2, severity = 'error' } = secondaryOption;
  return (root, result) => {
    root.walkRules(rule => {
      // 只检测类选择器,忽略 @keyframes 等
      if (!rule.selector.startsWith('.')) return;
      const decls = rule.nodes
        .filter(n => n.type === 'decl')
        .map(d => `${d.prop}:${d.value.trim()}`)
        .sort();
      if (!decls.length) return;
      const hash = createHash('md5').update(JSON.stringify(decls)).digest('hex');
      const loc = {
        file: root.source.input.from,
        line: rule.source.start.line,
        selector: rule.selector
      };
      cache.has(hash) ? cache.get(hash).push(loc) : cache.set(hash, [loc]);
    });
  };
});

// Stylelint 在所有文件跑完后会触发 OnceExit
module.exports.onceExit = function (results) {
  cache.forEach((locs, hash) => {
    if (locs.length >= 2) {
      // 取第一次出现的位置作为主报错点
      const target = locs[0];
      const rest = locs.slice(1).map(l => `\n  ${l.file}:${l.line} (${l.selector})`).join('');
      stylelint.utils.report({
        message: `重复样式块,共出现 ${locs.length} 次,其他位置:${rest}`,
        node: { source: { input: { from: target.file }, start: { line: target.line } } },
        result: results.find(r => r.source === target.file),
        ruleName: 'plugin/no-repeat-rules',
        severity: 'error'
      });
    }
  });
  cache.clear(); // 防止 watch 模式累积
});

第二步,在项目 .stylelintrc.js 中注册:

module.exports = {
  plugins: ['./plugins/no-repeat-rules'],
  rules: {
    'plugin/no-repeat-rules': [true, { threshold: 2, severity: 'error' }]
  }
};

第三步,集成到国内常用流水线:

# .github/workflows/lint.yml
- name: Install deps
  run: npm i -g stylelint postcss-scss
- name: Lint
  run: stylelint 'src/**/*.scss' --custom-syntax postcss-scss

若 MR 触发检测失败,GitLab/GitHub 均不可合并,实现「卡点」。

至此,Stylelint 就能在编译前阶段把「多组件重复构造相同样式表」精准揪出,并给出文件行列号,方便开发者统一抽离为公共 class 或 Design Token。

拓展思考

  1. 指纹算法升级:把 rgba(0,0,0,1) 与 #000 视为等价,需引入 postcss-value-parser 做数值归一化。
  2. 支持「语义级重复」:把 margin: 8px 0 8px 0 与 margin: 8px 0; 识别为相同,可再包一层 postcss-calc 简化。
  3. 自动抽离脚本:在 onceExit 阶段生成 repeat-report.json,交给 Node 脚本自动创建 packages/theme/_repeated.scss 并改写原文件 @import,实现「修复即重构」。
  4. 与「样式死代码」联动:同一插件再扫描「未被引用的 class」,一并输出,实现 Monorepo 级样式治理大盘。
  5. 性能优化:千级文件场景下,指纹缓存放 Redis,增量检测只跑 git diff --name-only 出的列表,5 秒内完成 MR 检查,满足国内快节奏迭代需求。