多入口
- 通過entry字段配置入口,例如
{
page1: './src/page1.js',
page2: './src/page2.js'
}
多出口,使用html-webpack-plugin
,有多少的出口就配置實例化多少個,同時通過chunks字段表示將那些chunk引入
new HtmlWebpackPlugin({
filename: 'page1.html',
template: 'page1.html',
inject: true,
title: 'page1',
chunks: ['page1','ventor'],
templateParameters: {
BASE_URL: config.build.assetsPublicPath + config.build.assetsSubDirectory,
},
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
}
}),
new HtmlWebpackPlugin({
filename: 'page2.html',
template: 'page2.html',
inject: true,
title: 'page2',
chunks: ['page2','ventor'],
templateParameters: {
BASE_URL: config.build.assetsPublicPath + config.build.assetsSubDirectory,
},
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
}
})
多出口的分包,主要藉助optimization.splitChunks
例如page1頁面使用vue、vuex、echart,page2應用使用了vue、vuex。
- 首先這兩頁面使用公共包有vue和vuex,所以這要拆分成公共包
- page1使用了echart,page2沒有使用,所以page2不要引入不相關的包
- 同時要結合
html-webpack-plugin
的chunks或者excludeChunks來表示包含或者排除那些chunk - 最後就是要對runtime的js拆分,不同的出口引入不同runtime運行代碼,此處通過runtimeChunk設置爲true或則multiple,詳情可見webpack官網文檔
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
ventor: {
name: 'ventor',
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: 'initial' // 只打包初始時依賴的第三方
},
echart: {
name: 'chunk-echart',
test: /[\\/]node_modules[\\/]echart[\\/]/,
priority: 20, // 權重要ventor的權重高,優先級要更高,不然就打到ventor裏面了
}
}
},
runtimeChunk: true,
minimizer: [
new UglifyJsPlugin({
uglifyOptions: {
mangle: {
safari10: true
}
},
sourceMap: config.build.productionSourceMap,
cache: true,
parallel: true
})
]
}
開發環境,config.dev.js
配置
- 開發環境,只開放一個入口一個出口,通過入口配置文件來控制,例如:
module.exports = {
page1: './src/page1.js',
page2: './src/page2.js'
}
- 通過入口配置文件來控制出口,即控制實例化多少個
html-webpack-plugin
, 由於出口的html名字不同,所以要根據入口動態配置下devServer的首頁html, 即devServer.index = 'index.html' // 默認
借鑑的文檔: