如何在 HTML 模板中引用特定 chunk 的资源?
解读
面试官问的不是“把打包后的文件手动拷进 HTML”,而是“在自动化构建流程里,让 HTML 模板精确地、只引入我想要的 chunk”。
国内项目常见场景:
- 多页应用(MPA),每个页面只加载自己的 runtime、vendor、page 三个 chunk,不能把兄弟页面的 chunk 带进来。
- 微前端基座,只加载基座 runtime 和 portal chunk,子应用 chunk由 qiankun 动态注入。
- 服务端渲染(SSR),HTML 由 Node 直出,客户端只补充 async chunk,避免重复加载。
如果候选人只说“html-webpack-plugin 会自动插”,会被追问“如何插指定的、如何去掉多余的、如何加 crossorigin、如何加 nonce、如何做内联”。
因此,答案必须覆盖:chunk 的命名、过滤、排序、模板变量、内联、属性扩展、多实例配置、与 SplitChunksPlugin 的联动。
知识点
- chunk 命名:entry 的 dependOn、splitChunks.name、magic comment /* webpackChunkName: "xxx" */。
- html-webpack-plugin 的 chunks、excludeChunks、chunksSortMode 配置。
- 模板引擎(ejs、lodash、handlebars)中使用的变量:htmlWebpackPlugin.files、htmlWebpackPlugin.tags、webpack.assetsByChunkName。
- 自定义 templateParameters 函数,可二次加工 assets 列表。
- 多实例:new HtmlWebpackPlugin({ filename: 'a.html', chunks: ['a'] })。
- 内联:html-inline-script-webpack-plugin 或自定义 alterAssetTags 钩子,把 runtime~xxx.js 转成 <script nonce="xxxx">code</script>。
- 属性扩展:scriptLoading='blocking' | 'defer' | 'module',crossorigin、integrity、nonce。
- 与 Webpack5 的 Asset Modules、experiments.lazyCompilation 联动,确保 async chunk 的 preload/prefetch 标签也能被精确控制。
答案
“分三步走:先让 chunk 有稳定名字,再让插件只吐出我想要的,最后在模板里精准引用。
第一步,命名:
entry: {
portal: { import: './src/portal.js', dependOn: 'shared' },
shared: 'react+react-dom'
}
optimization.splitChunks.cacheGroups.vendor.name = 'vendor';
路由懒加载文件用 /* webpackChunkName: "async-poi" */。
第二步,过滤:
new HtmlWebpackPlugin({
filename: 'portal.html',
template: './public/portal.ejs',
chunks: ['shared', 'vendor', 'portal'], // 仅保留这三
chunksSortMode: 'manual', // 按数组顺序
scriptLoading: 'defer',
crossorigin: 'anonymous'
})
第三步,模板里引用:
<% for (const js of htmlWebpackPlugin.files.js) { %>
<% } %>
如果想把 runtimeportal.js 内联,用 alterAssetTags 钩子:portal')) {
compiler.hooks.compilation.tap('InlineRuntimePlugin', (compilation) => {
const htmlPlugin = compilation.options.plugins.find(p => p.constructor.name === 'HtmlWebpackPlugin');
htmlPlugin.constructor.getHooks(compilation).alterAssetTags.tap('InlineRuntimePlugin', (data) => {
data.assetTags.scripts = data.assetTags.scripts.map(tag => {
if (tag.attributes.src.includes('runtime
const source = compilation.assets[tag.attributes.src.replace(publicPath,'')].source();
return { tagName: 'script', voidTag: false, innerHTML: source, attributes: { nonce: 'abc123' } };
}
return tag;
});
});
});
这样,portal.html 里只有 shared、vendor、portal 三个 chunk,runtime 被内联并带 nonce,其余 chunk 不会被误引入。”
拓展思考
- 如果页面需要动态插入子应用 chunk,而子应用由独立仓库构建,如何保证基座 HTML 不重复加载 vendor?
答:基座把 vendor 设为 external,子应用构建时把 react、react-dom 指向 window.React,基座 HTML 只保留一份 vendor.js,子应用 chunk 通过 Module Federation 或 qiankun 的 execScripts 加载,避免双份。 - 在 HTTP2 多路复用场景,是否还需要合并 vendor?
答:国内 CDN 多数已支持 HTTP2,可把 vendor 拆成 20~30KB 的小 chunk,利用 SplitChunks.minSize=20000,让浏览器并行加载,提升首屏;html-webpack-plugin 的 prefetch 标签可自动注入,无需手动写。 - 如何给不同环境(测试、预发、生产)注入不同的 publicPath,且保证 HTML 模板一次编写?
答:使用 html-webpack-plugin 的 base 选项或 templateParameters 注入 PUBLIC_PATH 变量,在 CI 里通过 cross-env PUBLIC_PATH=https://cdn.example.com npm run build,模板里写 <script src="<%= PUBLIC_PATH %><%= chunk %>">,实现“模板不动,路径随行”。