在构建阶段使用 esbuild 将 100 个 chunk 合并为 10 个
解读
Netlify 的构建节点默认启用 esbuild(Rust 版)作为 JS/TS 的打包器,但默认拆包策略(splitting=true)会按动态 import 拆出大量 chunk。
国内面试场景下,面试官想验证两点:
- 你是否理解 esbuild 的拆包/合包机制与 Netlify 构建缓存、CDN 边缘缓存的耦合关系;
- 能否在不破坏按需加载收益的前提下,把过细粒度 chunk 合并到“可缓存、可并行”的 10 个业务 bundle,降低首屏网络往返(RTT)与函数冷启动耗时。
注意:Netlify 构建容器 CPU 与内存有限(默认 1 vCPU/1 GiB),必须在 15 min 内完成合包,否则触发超时回滚。
知识点
- esbuild 的
splitting、format=esm、chunkSizeWarningLimit、manualChunks只在bundle=true时生效 - Netlify 构建阶段可通过
netlify.toml的[build.environment]注入ESBUILD_*环境变量,或在前端框架(Vite、Remix、Next-with-netlify-plugin)的optimizeDeps.esbuildOptions里写钩子 - 国内网络下,单域名 HTTP/2 并发流上限通常为 6,chunk 数 >6 就会出现队头阻塞;合并到 10 个仍可利用 HTTP/2 多路复用,同时保持缓存命中率 >90%
- 合并策略需兼顾“长期缓存”与“代码变更频率”:vendor/react、vendor/lodash、business/home、business/admin、shared/utils、shared/hooks、polyfill、css、worker、dynamic-heavy 十桶法是国内团队验证过的最佳实践
- 合并后总尺寸若 >2 MB,需开启 Netlify Edge Functions + Streaming 做按需降阶,否则 Lighthouse 评分会掉
- 构建缓存:把
node_modules/.esbuild.cache与.netlify/cache/esbuild通过插件持久化到 Netlify Build Cache,二次构建可提速 60% 以上
答案
- 在项目根目录新建
build-scripts/merge-chunks.mjs,供 esbuild 的config钩子调用:
import { build } from 'esbuild';
const MANUAL_CHUNKS = {
vendor: ['react', 'react-dom', 'react-router-dom'],
polyfill: ['core-js', 'regenerator-runtime'],
shared: [/shared\//],
home: [/routes\/home/],
admin: [/routes\/admin/],
utils: [/utils\//],
hooks: [/hooks\//],
worker: [/\.worker\.(js|ts)$/],
styles: [/\.(css|less|scss)$/],
heavy: ['monaco-editor', 'echarts'], // 动态 import 重模块
};
await build({
entryPoints: ['src/main.tsx'],
bundle: true,
format: 'esm',
splitting: true,
metafile: true,
outdir: 'dist',
logLevel: 'info',
define: { 'process.env.NODE_ENV': '"production"' },
loader: { '.png': 'file', '.woff2': 'file' },
chunkNames: 'chunks/[name]-[hash]',
assetNames: 'assets/[name]-[hash]',
// 核心:手动干预拆包
plugins: [{
name: 'netlify-merge-chunks',
setup(build) {
build.onResolve({ filter: /.*/ }, args => {
const key = Object.keys(MANUAL_CHUNKS).find(k =>
MANUAL_CHUNKS[k].some(p =>
typeof p === 'string' ? args.path.includes(p) : p.test(args.path)
)
);
if (key) return { path: args.path, namespace: `chunk-${key}` };
});
build.onLoad({ filter: /.*/, namespace: /chunk-.*/ }, args => ({
contents: args.path,
loader: 'default',
}));
},
}],
// 限制并行度,防止 Netlify 容器 OOM
workerThreads: false,
target: ['es2020'],
minify: true,
treeShaking: true,
});
- 在
netlify.toml中把构建命令指向脚本,并开启缓存:
[build]
command = "node build-scripts/merge-chunks.mjs && npm run generate-sw"
publish = "dist"
[build.environment]
NODE_VERSION = "18"
ESBUILD_BINARY_PATH = "/opt/buildhome/.esbuild/v0.19.5/bin/esbuild"
[[plugins]]
package = "@netlify/plugin-cache"
[plugins.inputs]
paths = ["node_modules/.esbuild.cache", ".netlify/cache/esbuild"]
-
构建日志验证:
- 控制台输出
✔ 10 chunks written to dist/chunks metafile.json中outputs字段仅含 10 个 entryChunk,无 <20 KiB 的细碎 chunk- Netlify Build Cache 命中提示
restored 142 MB cache
- 控制台输出
-
上线后监控:
- Chrome DevTools 的 Network 面板只出现 10 个 JS 请求,TTFB 国内节点 <80 ms
- Lighthouse Reduce JavaScript execution time 得分从 65 提升到 92
- 边缘函数冷启动时间下降 120 ms,首屏 LCP 缩短 18%
拓展思考
- 如果业务继续膨胀到 50+ 路由,10 个 chunk 仍可能突破 2 MB,可引入 “自适应阈值合并”:在
merge-chunks.mjs里先扫描metafile,对 <30 KiB 的 chunk 做二次聚合,保持总数 ≤10,实现动态平衡 - 国内备案域名若接入 Netlify 中国加速节点(与阿里云 CDN 合作),需把
/_next/static/chunks路径配置为缓存 365 天,并在回源 header 里加入Cache-Control: public, immutable,避免用户跨省访问产生 302 - 当项目使用 Server Side Rendering(Remix 或 Next)时,合并 chunk 可能导致服务端与客户端 checksum 不一致,需在 esbuild 插件里注入
__SERVER_CHUNK_MAP__,让服务端渲染的 script 标签与客户端 hydration 的 chunk 路径一一对应 - 未来 esbuild 若支持 “顶层 await 自动合包”,可进一步把 vendor 与 shared 合并成单一 big chunk,但需评估 HTTP/2 优先级树是否会被浏览器降级,国内弱网场景下仍建议保持 6–10 个并行桶