项目文件结构:
├─build
├ ├─webpack.base.js
├ ├─webpack.dev.js
├ └─webapck.prod.js
├─package.json
├
├─src
└─views
├─admin
├ ├─index.js
├ └─index.html
└─client
├─index.js
└─index.html
entry
配置
开发环境(dev
):
entry: {
admin: [
resolve('./src/views/admin/index.js'),
'webpack-hot-middleware/client?quiet=true' // 如果是通过webpack-hot-middleware启动热更新的,需要加上热更新的客户端
],
client: [
resolve('./src/views/client/index.js'),
'webpack-hot-middleware/client?quiet=true' // 如果是通过webpack-hot-middleware启动热更新的,需要加上热更新的客户端
]
}
生产环境(prod
):
entry: {
admin: [
resolve('./src/views/admin/index.js')
],
client: [
resolve('./src/views/client/index.js')
]
}
output
配置
output: {
filename: '[name].[hash:8].js', // 因为是多应用,所以必须通过名称匹配的方式生成打包文件
path: './dist',
publicPath: '/'
}
html
配置
因为是多页面应用,所以每个应用都有一个独立的html
文件
通过html-webpack-plugin
插件来配置,需要达到以下目标:
- 每个
html
文件只加载对应应用需要的依赖包 - 可以根据不同环境加载不一样的依赖包
开发环境(dev
):
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: resolve('./src/views/admin/index.html'),
chunks: ['admin'], // 设置chunks可以只安装指定的依赖包,如果不设置,则会将所有依赖包全部加载
inject: true
}),
new HtmlWebpackPlugin({
filename: 'client.html',
template: resolve('./src/views/client/index.html'),
chunks: ['client'], // 设置chunks可以只安装指定的依赖包,如果不设置,则会将所有依赖包全部加载
inject: true
})
]
生产环境(prod
):
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: resolve('./src/views/admin/index.html'),
chunks: ['admin'],
inject: true,
minify: true // 压缩文件
}),
new HtmlWebpackPlugin({
filename: 'client.html',
template: resolve('./src/views/client/index.html'),
chunks: ['client'],
inject: true,
minify: true // 压缩文件
})
]
如果在设置了公共包或者配置了
optimization: {runtimeChunk: 'single'}
这时,在chunks
中一定要加入这些依赖包
如:chunks: ['runtime', 'common', 'amdin']