如何检测 background-image 使用 png/jpg 而未提供 webp?

解读

国内大厂对 Web 性能考核越来越严,首屏图片体积直接关联业务 KPI。面试官抛出此题,表面看是“写一条规则”,实则考察三层能力:

  1. 对 Stylelint 插件机制(PostCSS 抽象语法树、遍历钩子、自定义消息)的掌握深度;
  2. 对国内主流构建流程(Webpack/Vite + GitHub Actions + 云测性能卡口)的理解;
  3. 工程化落地经验:如何在不改变设计师交付习惯的前提下,用自动化工具把“必须提供 WebP 回退”做成门禁,而非口头规范。
    若只答“用 stylelint-value-no-unknown-custom-properties”或“正则匹配 url()”只能拿基础分;必须给出完整插件骨架、AST 定位策略、自动修复思路、与 CI 性能基线的联动,才能打动面试官。

知识点

  1. PostCSS AST 节点类型:Decl→value→func(url)→string,需递归 valueParser 识别 url(...) 函数。
  2. Stylelint 插件三件套:
    ruleName 命名空间(plugin/xxx)、createPlugin 工厂、utils.report 上报。
  3. 国内常用图片 CDN 多带 ?format=webp 参数,需同时识别相对路径、绝对路径、queryString 三种写法。
  4. 自动修复(fix)接口:通过 utils.fix() 返回同名 *.webp 文件,若存在则替换,否则降级提示。
  5. 性能门禁:在 GitHub Actions 中把 stylelint 结果输出为 junit.xml,由内部云测平台解析,若出现 webp-missing 错误则阻断合并。
  6. 规则分级:warning 仅提示,error 阻断流水线;可通过 secondaryOption 控制 { severity: 'error', enforceFix: true }。
  7. 与设计师协作:输出缺失 WebP 清单到飞书群机器人,自动 @对应 UI 同学,形成闭环。

答案

  1. 实现插件 stylelint-plugin-webp-enforce
// stylelint-plugin-webp-enforce/index.js
const stylelint = require('stylelint');
const valueParser = require('postcss-value-parser');
const { existsSync } = require('fs');
const { resolve, dirname } = require('path');

const ruleName = 'plugin/webp-enforce';
const messages = stylelint.utils.ruleMessages(ruleName, {
  missingWebP: (pngPath) => `必须提供对应的 WebP 文件:${pngPath}.webp`,
});

module.exports = stylelint.createPlugin(ruleName, (primaryOption, secondaryOption = {}) => {
  return (root, result) => {
    if (!primaryOption) return;
    const severity = secondaryOption.severity || 'error';
    root.walkDecls(decl => {
      if (decl.prop !== 'background-image') return;
      valueParser(decl.value).walk(node => {
        if (node.type !== 'function' || node.value !== 'url') return;
        const urlNode = node.nodes[0];
        if (!urlNode || urlNode.type !== 'string') return;
        let url = urlNode.value.replace(/['"]/g, '');
        // 去掉 query
        const cleanUrl = url.split('?')[0];
        if (!/\.(png|jpe?g)$/i.test(cleanUrl)) return;
        const cssFileDir = dirname(decl.source.input.file);
        const webpPath = resolve(cssFileDir, cleanUrl + '.webp');
        if (!existsSync(webpPath)) {
          stylelint.utils.report({
            message: messages.missingWebP(cleanUrl),
            node: decl,
            result,
            ruleName,
            severity,
            line: decl.source.start.line,
            column: decl.source.start.column,
          });
        }
      });
    });
  };
});
  1. 注册到 .stylelintrc.js
module.exports = {
  plugins: ['./stylelint-plugin-webp-enforce'],
  rules: {
    'plugin/webp-enforce': [true, { severity: 'error' }],
  },
};
  1. 本地验证
npx stylelint "src/**/*.{css,scss}" --formatter github

若缺失 WebP,终端输出:

src/components/banner/index.scss
 15:3  ✖  必须提供对应的 WebP 文件:./assets/bg.png.webp  plugin/webp-enforce
  1. CI 门禁
    在 GitHub Actions 中:
- run: npx stylelint src --formatter github
  env:
    FAIL_ON_ERROR: true

云测平台解析 annotations,若存在 error 级别则合并请求被阻断,并同步飞书卡片。

拓展思考

  1. 自动修复:在插件中增加 fix 函数,调用 imagemin-webp 把 png/jpg 批量生成 webp,并回写 css 为 image-set(url(bg.png) 1x, url(bg.webp) 1x type("image/webp")),实现无感知升级。
  2. 多语言模板:在 Vue/React 代码里用 style={{ backgroundImage: 'url(~@/assets/bg.png)' }} 同样需检测,可扩展为遍历 TemplateLiteral 与 JSXAttribute。
  3. 国内小程序场景:微信/支付宝小程序的 wxss/acss 也走 PostCSS,可把该插件打包到 miniprogram-ci,在上传前做云构建校验,防止大图片拖慢首屏。
  4. 设计交付规范:把 WebP 缺失清单自动同步到蓝湖/摹客标注平台,生成“待切图”任务,UI 同学一键导出即可,无需手工维护 Excel。
  5. 灰度策略:通过 secondaryOption 设置白名单目录,如 exclude: ['**/legacy/**'],让老业务渐进式改造,避免一次性阻塞全量代码。