如何统计项目中被添加的 flex 前缀总量?

解读

面试官想确认三件事:

  1. 你是否真正理解 Autoprefixer 只是 PostCSS 的一个插件,而不是“魔法”;
  2. 你是否能在不破坏现有构建流程的前提下,把“统计”做成一个可插拔的 PostCSS 插件;
  3. 你是否能把统计结果落地到 CI/脚本,方便国内常见的“走查报告”“代码健康度”场景。

因此,答案必须给出“可运行、可集成、可解释”的完整方案,而不是一句“看构建日志”。

知识点

  • PostCSS 插件协议:插件是一个函数,接收 root 和 result,通过 Once/Rule/Decl 访问器遍历 AST;
  • Autoprefixer 的 AST 时机:它在 PostCSS 插件链里把新节点插到原节点前后,因此统计必须在 Autoprefixer 之后执行;
  • 前缀判定规则:国内浏览器矩阵通常要兼容 iOS 9、Android 5、微信 X5 内核,因此 -webkit-box、-webkit-flex、-ms-flexbox 都算;
  • 结果输出:CI 场景需要结构化数据(JSON),走查报告需要人读(Markdown),性能场景需要行号便于定位;
  • 性能:项目上万行 CSS 时,插件本身耗时必须 < 50 ms,不能二次序列化 CSS。

答案

  1. 新建一个只负责统计的 PostCSS 插件 postcss-flex-prefix-counter,代码如下:
const plugin = require('postcss').plugin;

module.exports = plugin('postcss-flex-prefix-counter', (opts = {}) => {
  const { output = 'flex-prefix.json', onFinish } = opts;
  const stat = { total: 0, details: [] };

  return {
    postcssPlugin: 'postcss-flex-prefix-counter',
    OnceExit(root, { result }) {
      root.walkDecls(decl => {
        const isFlexProp = /^(display|flex|justify-content|align-items|flex-direction|flex-wrap)/.test(decl.prop);
        if (!isFlexProp) return;

        const hasPrefix = decl.value.includes('-webkit-') || decl.value.includes('-ms-') ||
                          decl.prop.startsWith('-webkit-') || decl.prop.startsWith('-ms-');
        if (hasPrefix) {
          stat.total += 1;
          stat.details.push({
            file: root.source?.input.file || 'unknown',
            line: decl.source?.start?.line,
            prop: decl.prop,
            value: decl.value
          });
        }
      });

      if (onFinish) onFinish(stat);
      else require('fs').writeFileSync(output, JSON.stringify(stat, null, 2));
    }
  };
});
  1. 在 postcss.config.js 里把该插件放到 Autoprefixer 之后:
module.exports = {
  plugins: [
    require('autoprefixer'),
    require('./postcss-flex-prefix-counter')({
      output: 'reports/flex-prefix.json'
    })
  ]
};
  1. 在 package.json 中补充脚本,兼容国内常用的“走查”流程:
"scripts": {
  "build:stat": "cross-env NODE_ENV=production webpack --config webpack.prod.js",
  "report:flex": "node -e \"const r=require('./reports/flex-prefix.json'); console.log('共添加 flex 相关前缀 %d 处', r.total)\""
}
  1. 运行 npm run build:stat && npm run report:flex,即可在控制台与 JSON 文件同时拿到总量与定位信息,方便后续插入企业微信机器人或钉钉群通知。

拓展思考

  1. 如果项目使用 Vite,可直接把插件塞进 vite.config.ts 的 css.postcss.plugins 数组,无需改 webpack;
  2. 对于微前端仓库群,可在 CI 里把各子应用统计文件上传到内部 Nexus 私服,再写一个小脚本做聚合,输出“本月新增 flex 前缀 TOP10 仓库”;
  3. 进一步可扩展成“前缀成本”指标:把每个前缀对应的 gzip 体积增量算出来,推动业务方用 “display: flex” 替代 “display: -webkit-box”,从而真正减少字节;
  4. 若公司强制要求“零前缀”规范,可把该插件改造成警告模式:总量 > 0 时 process.exit(1),直接在 MR 阶段拒绝合并,实现“左移”治理。