如何为每个构建产物生成 SHA256 校验和?
解读
面试官问的不是“能不能”,而是“怎么做、做得稳、做得快”。
国内一线团队普遍把产物校验和作为上线门禁:
- 灰度/回滚时比对 Hash,秒级判断包是否被篡改;
- 与 CDN 的“子资源完整性(SRI)”配合,防运营商缓存投毒;
- 作为 CI 产物指纹,直接写入 OSS/Artifactory,实现“同 hash 不重复上传”,节省存储与流量。
因此,回答要覆盖:
- 构建阶段如何拿到最终文件名与内容;
- 如何高性能地算 SHA256;
- 如何落盘(json、manifest、上传到服务端);
- 如何与 Webpack5 的“持久化缓存”及“并发编译”兼容;
- 如何不破坏 SourceMap、不重复读盘、不拖慢 CI。
知识点
- Webpack 插件生命周期:emit → afterEmit → done;
- compilation.assets 对象:key 为最终文件名,value 为 {source(), size()};
- crypto.createHash('sha256') 流式计算,避免 Buffer 拼接;
- Webpack5 的 RawSource / CachedSource 与缓存策略;
- 并发任务控制(p-limit、p-map)防止同时打开数千文件句柄;
- 国内 CI 常见镜像(GitHub Actions + 腾讯云 COS、阿里云 OSS、华为云 SWR)的校验和上传 API;
- SRI 格式:sha256-xxx…xxx,需 base64 编码而非 hex;
- 合规要求:国密 SM3 场景下的可插拔改造思路。
答案
“我会写一个 Webpack5 插件,在 afterEmit 阶段并行生成每个产物的 SHA256,并输出一份 hash-manifest.json,供上线系统与 CDN 校验。”
核心代码(TypeScript):
import { createHash } from 'crypto';
import { readFile } from 'fs/promises';
import { join } from 'path';
import { Compilation, Compiler, WebpackPluginInstance } from 'webpack';
const PLUGIN_NAME = 'WebpackSHA256Plugin';
export class WebpackSHA256Plugin implements WebpackPluginInstance {
private readonly algorithm: string;
private readonly outputPath: string;
constructor(options: { algorithm?: string; outputPath?: string } = {}) {
this.algorithm = options.algorithm || 'sha256';
this.outputPath = options.outputPath || 'hash-manifest.json';
}
apply(compiler: Compiler): void {
compiler.hooks.afterEmit.tapPromise(PLUGIN_NAME, async (compilation: Compilation) => {
const hashMap: Record<string, string> = {};
const outputPath = compilation.outputOptions.path!;
// 只处理“最终要写到磁盘”的 asset
const assets = Object.keys(compilation.assets).filter(name =>
// 过滤掉已经被标记为“跳过”的 SourceMap
!name.endsWith('.map')
);
// 控制并发,防止 CI 把文件句柄打满
const limit = require('p-limit')(200);
await Promise.all(
assets.map(name =>
limit(async () => {
const abs = join(outputPath, name);
const content = await readFile(abs);
const hash = createHash(this.algorithm).update(content).digest('hex');
hashMap[name] = hash;
})
)
);
// 写入 manifest
const manifestContent = JSON.stringify(hashMap, null, 2);
const manifestPath = join(outputPath, this.outputPath);
await require('fs/promises').writeFile(manifestPath, manifestContent);
// 同时把 manifest 也注册到 assets,让 Webpack 知道它参与了构建
compilation.assets[this.outputPath] = {
source: () => manifestContent,
size: () => manifestContent.length,
} as any;
});
}
}
使用:
// webpack.prod.js
const { WebpackSHA256Plugin } = require('./plugins/WebpackSHA256Plugin');
module.exports = {
// …
plugins: [
new WebpackSHA256Plugin({ outputPath: 'sha256.json' }),
],
};
CI 侧读取 dist/sha256.json,与上一次灰度包对比,若一致则直接复用 CDN 缓存,否则触发新上传。
拓展思考
-
速度优化:
- 利用 Webpack5 的
compilation.getCache()把已算过的 hash 缓存到.webpack-cache,二次构建秒级跳过; - 对超过 50 MB 的大文件使用流式读盘 + worker_threads,防止阻塞主事件循环。
- 利用 Webpack5 的
-
完整性闭环:
- 把 hash 写入
index.html的<meta name="build-hash" content="...">,前端报错日志直接带上,方便 Sentry 回溯; - 在 OSS 上传完成后,调用“云 API-校验上传”接口,把 hash 作为
x-oss-hash-crc64的比对值,防止中间人篡改。
- 把 hash 写入
-
合规与降级:
- 金融类客户要求国密 SM3,可把
createHash('sha256')换成require('sm-crypto').sm3,通过插件参数切换; - 若项目仍用 Webpack4,需把
afterEmit换成emit并手动compilation.assets[manifest].emit = true,避免漏写。
- 金融类客户要求国密 SM3,可把
-
微前端场景:
- 主应用需要子应用 hash,可在 ModuleFederation 的
exposes列表里同样跑一遍插件,最后聚合到同一sha256.json,实现“主子同表”。
- 主应用需要子应用 hash,可在 ModuleFederation 的