文件结构:
src: index.html , other.html , index.js , other.js
配置文件:
文件内容:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>index page</p>
</body>
</html>
index.js
console.log('index')
other.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>other page</p>
</body>
</html>
other.js
console.log('other')
path.js
/**
* @description 常用文件夹路径
* @author 山间
*/
const path = require('path')
const srcPath = path.join(__dirname, '..', 'src')
const distPath = path.join(__dirname, '..', 'dist')
module.exports = {
srcPath,
distPath
}
接下来看如何配置:
第一步:修改 webpack.common.js 的入口配置
entry 这块的单一入口就需要从 path.join(srcPath, 'index') 修改为多入口
const path = require('path')
const { srcPath, distPath } = require('./paths')
module.exports = {
// ...
// entry: path.join(srcPath, 'index'),
entry: {
index: path.join(srcPath, 'index.js'),
other: path.join(srcPath, 'other.js')
}
// ...
}
第二步:修改出口配置,即 output 的配置,那是在 webpack.prod.js 中
const path = require('path')
const { srcPath, distPath } = require('./paths')
module.exports = {
// ...
output: {
filename: '[name].[contenthash:8].js', // name 即多入口时 entry 的 key,在这里就是 index 和 other
path: distPath
}
// ...
}
第三步:因为有两个页面,所以需要在 webpack.common.js 中配置多入口的 HtmlWebpackPlugin
// ...
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
// ...
plugins: [
// 多入口 - 生成 index.html
new HtmlWebpackPlugin({
template: path.join(srcPath, 'index.html'),
filename: 'index.html',
// chunks 表示该页面引用哪些 chunk (即上面的 index 和 other)
// 如果不写 chunks , 会把入口的两个 chunk - index 和 other 都引入
chunks: ['index'] // 只引用 index.js
}),
// 多入口 - 生成 other.html
new HtmlWebpackPlugin({
template: path.join(srcPath, 'other.html'),
filename: 'other.html',
chunks: ['other']
})
]
}
好了,一共就这三步配置,就可以实现 Webpack 的多入口啦。总结一下,首先是配置 entry ,然后是 output ,最后配置多页面。
配置好以后可以尝试 run 和 build 一下,可以看到在页面中,index.html 只会引入 index.js,other.html也是只会引入 other.js;在打包的dist文件夹中,会打包出index.html、index[contenthash:8].js、other.html、other[contenthash:8].js 四个文件。