
本文介绍如何在 webpack 5 中通过多入口配置与 htmlwebpackplugin 精确控制不同 html 文件所加载的 js 资源,实现“1.html 加载 main.js 和 123.js,2.html 仅加载 main.js”的按需打包需求。
在 Webpack 5 中,若需为不同 HTML 页面注入不同的 JS 包(例如让 1.html 同时引入 main.js 和 123.js,而 2.html 仅引入 main.js),核心思路是:定义多个入口(multi-entry),再借助 HtmlWebpackPlugin 的 chunks 选项显式指定每个 HTML 所需的代码块。
✅ 正确配置步骤
- 设置多入口对象:将 main.js 和 123.js 分别声明为独立入口,Webpack 会为它们生成对应的输出文件(如 main.js、oneTwoThree.js);
- 为每个 HTML 实例化 HtmlWebpackPlugin:通过 filename 指定生成的 HTML 名称,用 chunks 数组精确声明该页面应包含哪些入口生成的 JS;
- 配置 output.filename 使用 [name] 占位符:确保输出文件名与入口名一致,便于 HtmlWebpackPlugin 正确关联。
以下为完整、可直接运行的 webpack.config.js 示例(需提前安装依赖):
npm install --save-dev webpack webpack-cli html-webpack-plugin
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'production', // 或 'development'
entry: {
main: './main.js',
oneTwoThree: './123.js' // 自定义 chunk 名,对应输出文件名
},
plugins: [
// 生成 1.html,同时注入 main.js 和 oneTwoThree.js
new HtmlWebpackPlugin({
filename: '1.html',
template: './1.html', // 可选:复用原始 HTML 模板(推荐)
chunks: ['main', 'oneTwoThree']
}),
// 生成 2.html,仅注入 main.js
new HtmlWebpackPlugin({
filename: '2.html',
template: './2.html',
chunks: ['main']
})
],
output: {
filename: '[name].[contenthash:8].js', // 推荐添加 contenthash 实现长效缓存
path: path.resolve(__dirname, 'dist'),
clean: true // Webpack 5+ 自动清理 dist 目录
}
};⚠️ 注意事项
- template 选项建议显式指定(如 template: './1.html'),否则插件会生成默认空白 HTML;原始 HTML 中无需手动写 ,HtmlWebpackPlugin 会自动注入;
- chunks 数组中的名称必须与 entry 对象的键名完全一致(区分大小写);
- 若 123.js 仅被部分页面使用,且无其他依赖关系,不建议将其 import 到 main.js 中,否则会强制合并进 main.js,失去按需加载意义;
- 如需进一步优化,可结合 SplitChunksPlugin 提取公共模块,或使用 dynamic imports 实现运行时懒加载(适用于更复杂场景)。
通过以上配置,执行 npx webpack 后,dist/ 目录将生成:
dist/ ├── main.a1b2c3d4.js ├── oneTwoThree.e5f6g7h8.js ├── 1.html ← 自动包含 和 └── 2.html ← 仅包含
这种方案简洁、可控、符合 Webpack 最佳实践,特别适合多页应用(MPA)中精细化资源管理的需求。
立即学习“前端免费学习笔记(深入)”;











