如何限制单个选择器使用超过 3 个 will-change?

解读

面试官抛出这道题,核心想验证三件事:

  1. 你是否意识到 will-change 属于“高危性能属性”,滥用会直接触发 GPU 内存暴涨、帧率骤降;
  2. 你是否具备“把业务约束转成自动化规则”的工程化思维,而不是口头劝同事“别写太多”;
  3. 你是否熟悉 Stylelint 插件机制,能在不依赖现成规则的情况下,用 AST 精准计数并给出可修复方案。

国内大厂(阿里、腾讯、字节)的面试风格是“原理+落地”并重,答出“写个插件”只是及格线,还要讲清 AST 遍历策略、错误定位、自动修复、与 CI 的集成、对旧代码的灰度策略,才能拿到高分。

知识点

  1. will-change 的副作用
    ‑ 每多一个属性,浏览器就为其独立分配合成层(layer);>3 个时移动端 WebView 极易 OOM。
  2. Stylelint 插件最小单元
    ‑ 基于 PostCSS AST,入口是 root.walkRules();每条 rule.selector 可能含多个并列选择器,需先 selectorParser() 拆成独立节点。
  3. 计数策略
    ‑ 只统计同一“逻辑选择器”内的 will-change 声明次数;@media 嵌套、父子选择器要视为不同作用域,防止误报。
  4. 自动修复
    ‑ 通过 context.fix 标志,把多余的属性删除或合并成一条,并提示开发者用 contain 或 transform: translateZ(0) 替代。
  5. 国内工程链
    ‑ 规则包必须发公司私有 npm,并在 @company/stylelint-config 中默认开启;配合 husky + lint-staged 在 MR 阶段拦截,禁止 --no-verify 绕过。

答案

  1. 初始化插件骨架
// stylelint-plugin-will-change-limit/index.js
const stylelint = require('stylelint');
const { plugin, ruleMessages } = stylelint.utils;
const selectorParser = require('postcss-selector-parser');

const ruleName = 'plugin/will-change-limit';
const messages = ruleMessages(ruleName, {
  expected: (selector, count) =>
    `选择器 "${selector}" 使用了 ${count} 个 will-change,超过最大允许 3 个`,
});

const meta = {
  url: 'https://github.com/company/stylelint-plugin-will-change-limit',
  fixable: true,
};

module.exports = stylelint.createPlugin(ruleName, (primaryOption, secondaryOption = {}, context) => {
  return (root, result) => {
    const max = primaryOption !== undefined ? primaryOption : 3;
    root.walkRules(rule => {
      // 跳过 @keyframes 等无意义节点
      if (rule.parent && rule.parent.type === 'atrule' && rule.parent.name === 'keyframes') return;

      let willChangeCount = 0;
      rule.walkDecls(decl => {
        if (decl.prop.toLowerCase() === 'will-change') {
          willChangeCount += decl.value.split(',').length;
        }
      });

      if (willChangeCount > max) {
        if (context.fix) {
          // 自动修复:只保留前 3 条
          let kept = 0;
          rule.walkDecls(decl => {
            if (decl.prop.toLowerCase() === 'will-change') {
              const props = decl.value.split(',').map(p => p.trim()).filter(Boolean);
              const left = props.slice(0, max - kept);
              kept += left.length;
              if (left.length) {
                decl.value = left.join(', ');
              } else {
                decl.remove();
              }
            }
          });
        } else {
          selectorParser(selectors => {
            const fullSelector = selectors.nodes.map(s => s.toString()).join(', ');
            stylelint.utils.report({
              message: messages.expected(fullSelector, willChangeCount),
              node: rule,
              result,
              ruleName,
              word: fullSelector,
            });
          }).processSync(rule.selector);
        }
      }
    });
  };
});
module.exports.ruleName = ruleName;
module.exports.messages = messages;
module.exports.meta = meta;
  1. 注册到项目配置
// .stylelintrc.js
module.exports = {
  plugins: ['./stylelint-plugin-will-change-limit'],
  rules: {
    'plugin/will-change-limit': [3, { severity: 'error' }],
  },
};
  1. 集成到 GitHub Actions(国内镜像源加速)
- name: Lint CSS
  run: |
    npm i -g --registry=https://registry.npmmirror.com stylelint
    stylelint "src/**/*.{css,scss,less}" --max-warnings 0
  1. 灰度策略
    ‑ 存量文件先 severity: 'warning',收集 7 天数据后把阈值降到 3 并改为 error;
    ‑ 对老业务开启 --fix 批量修复,MR 中必须展示性能对比(Lighthouse 图层数量)。

拓展思考

  1. 如果把“3”做成可共享的 JSON Schema,就能让设计系统统一收口:颜色动画只允许 will-change: opacity,位移动画只允许 transform,从规则层面彻底禁止“写一堆”。
  2. 可以扩展成“性能预算”插件:把 will-change 数量、层尺寸、合成层内存估算(通过 Chrome trace 公式)一起计算,超预算直接阻断流水线,实现“样式性能门禁”。
  3. 在微前端场景,子应用独立仓库,主应用运行时合并样式。此时需在 Stylelint 之上再包一层“多仓库聚合检查”服务,把各子应用报告汇总到看板,防止“单看都合格,合起来爆炸”。