如何为 `url()` 引用的图片自动添加哈希?

解读

面试官真正想考察的是:

  1. 你是否理解 PostCSS 的“AST 驱动”思想——不是正则替换,而是精准地找到 url() 节点;
  2. 你是否能把“哈希”这件事与前端工程化里的“缓存击穿”场景联系起来,并给出可落地的插件级方案;
  3. 你是否熟悉国内常见的构建链路(Vite / Webpack + CDN 上传),能把 PostCSS 插件无缝接入 CI/CD;
  4. 代码边界处理:别名路径、Base64、远程地址、单文件组件 <style> 块、CSS Modules 作用域等。

一句话:让你手写一个“生产可用”的 PostCSS 插件,在本地编译阶段把 background: url(./a.png) 变成 background: url(/static/img/a.7c4e8d.png),同时把文件复制到输出目录并返回最终 CDN 地址。

知识点

  1. PostCSS 插件八股结构:
    module.exports = (opts = {}) => {
      return {
        postcssPlugin: 'postcss-url-hash',
        Once(root, { result }) { /* 遍历入口 */ },
        Declaration(node) { /* 精确拦截声明 */ }
      }
    }
    
  2. 节点类型:Declaration → value 里再解析 url(),需用 postcss-value-parser 避免正则坑;
  3. 哈希算法:国内 CDN 普遍接受 8 位 md5(fileContent).slice(0, 8),兼顾可读性与缓存粒度;
  4. 路径解析:以 result.opts.from 拿到当前 CSS 文件绝对路径,再用 path.resolve() 定位图片真实位置;
  5. 输出目录:结合 compiler.outputPath(Webpack)或 build.outDir(Vite),用 fs.copyFileSync 同步拷贝并改名;
  6. 缓存与性能:使用 new Map() 做“文件→哈希”内存缓存,避免重复读盘;
  7. 差异化跳过:遇到 url('data:...')、url('https://...')、url('#id') 直接 return;
  8. SourceMap 友好:修改 node.value 后调用 node.prop = node.prop 触发 PostCSS 内部映射更新;
  9. 并发安全:在 OnceExit 钩子统一写盘,防止多线程打包(如 Webpack 的 thread-loader)出现竞态;
  10. 落地规范:阿里、腾讯 CDN 要求“哈希在前缀”形式,如 img/a.png → img/a_7c4e8d.png,避免中文域名转义问题。

答案

下面给出一个可直接放进 postcss.config.js 的完整插件,满足国内生产环境要求:

// postcss-url-hash.js
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const valueParser = require('postcss-value-parser');

const cache = new Map(); // 文件级缓存

module.exports = (opts = {}) => {
  const {
    hashLen = 8,
    publicPath = '/static/img/',
    outputDir = path.resolve('dist/static/img')
  } = opts;

  // 确保输出目录存在
  if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });

  return {
    postcssPlugin: 'postcss-url-hash',
    Once(root, { result }) {
      const cssFile = result.opts.from; // 当前 CSS 文件绝对路径
      const declarations = [];

      root.walkDecls(decl => {
        if (decl.value.includes('url(')) declarations.push(decl);
      });

      declarations.forEach(decl => {
        const parsed = valueParser(decl.value);
        let modified = false;

        parsed.walk(node => {
          if (node.type !== 'function' || node.value !== 'url') return;
          const urlNode = node.nodes[0];
          if (!urlNode || urlNode.type !== 'string' && urlNode.type !== 'word') return;

          let rawUrl = urlNode.value;
          if (/^data:|^https?:|^\/\/|^#/.test(rawUrl)) return; // 跳过 base64、远程、锚点

          const absolutePath = path.resolve(path.dirname(cssFile), rawUrl);
          if (!fs.existsSync(absolutePath)) return; // 文件不存在,交给下游处理

          const content = fs.readFileSync(absolutePath);
          let hash = cache.get(absolutePath);
          if (!hash) {
            hash = crypto.createHash('md5').update(content).digest('hex').slice(0, hashLen);
            cache.set(absolutePath, hash);
          }

          const { dir, name, ext } = path.parse(rawUrl);
          const newName = `${name}_${hash}${ext}`;
          const targetFile = path.join(outputDir, newName);

          if (!fs.existsSync(targetFile)) {
            fs.copyFileSync(absolutePath, targetFile);
          }

          urlNode.value = `${publicPath.replace(/\/$/, '')}/${newName}`;
          modified = true;
        });

        if (modified) decl.value = parsed.toString();
      });
    }
  };
};

module.exports.postcss = true;

使用方式(以 Vite 为例):

// postcss.config.js
module.exports = {
  plugins: [
    require('./postcss-url-hash')({
      publicPath: 'https://cdn.example.com/static/img',
      outputDir: path.resolve('dist/static/img')
    }),
    require('autoprefixer')
  ]
}

构建后,源码 background: url(./logo.png) 会被替换成 background: url(https://cdn.example.com/static/img/logo_7c4e8d.png),同时 dist/static/img/logo_7c4e8d.png 文件已就绪,可直接上传 CDN。

拓展思考

  1. 如果项目里用 ~@/assets/logo.png 这种 Webpack alias,需要在插件里提前读取 resolve.alias 配置,把 alias 展开成真实路径,否则哈希会失效;
  2. 微前端场景下,子应用 CSS 可能以 style 标签动态注入,此时 result.opts.from 为虚拟路径,需要与主应用的“资源表”做二次映射;
  3. 雪碧图与字体文件同样适用该插件,但字体要保留跨域头,需在 outputDir 里额外写 .htaccess 或 Access-Control-Allow-Origin 响应头;
  4. 若公司 CDN 要求“时间戳+哈希”双因子,可把 hash 换成 hash + ts,并在 CI 环境注入 process.env.BUILD_ID;
  5. 与 css-modules 混用时,插件应放在 postcss-modules 之前,防止类名哈希化后再改 url() 导致映射失效;
  6. 如果未来切到 ESM 构建,可把插件改写成 export default,并用 import { readFileSync } from 'fs' 享受 Tree-Shaking;
  7. 面试加分项:提到“已给公司内网 Nexus 私服贡献私有 PostCSS 插件,平均构建耗时降低 12%,CDN 回源率下降 35%”,用数据说话。