為什么要抽離公共模塊、第三方模塊?
多入口打包時引入公共部分,公共部分會進行重復(fù)打包,打包效率降低,打包文件體積變大;
第三方模塊不會改變,但頁面發(fā)生任何變動,第三方模塊都需要重新打包,通過抽離第三方模塊,頁面變動時命中緩存,只打包開發(fā)部分代碼,提升打包性能。
1. 將第三方模塊、公共模塊分別打包為chunk
將第三方模塊、公共模塊分別打包,分別產(chǎn)出對應(yīng)的chunk,以便按需引用;
將兩者均放在cacheGroups做緩存分組中,將包作為緩存使用,避免重復(fù)打包;
- optimization.splitChunks 進行分割代碼塊
- optimization.splitChunks.cacheGroups做緩存分組:第三方模塊、公共模塊
[webpack.prod.js]
optimization: {
// 分割代碼塊
splitChunks: {
chunks: 'all',
/**
* initial 入口 chunk,對于異步導(dǎo)入的文件不處理
async 異步 chunk,只對異步導(dǎo)入的文件處理
all 全部 chunk
*/
// 緩存分組
cacheGroups: {
// 第三方模塊
vendor: {
name: 'vendor', // chunk 名稱
priority: 1, // 權(quán)限更高,優(yōu)先抽離,重要!!!
test: /node_modules/, // 模塊的路徑
minSize: 0, // 大小限制
minChunks: 1 // 最少復(fù)用過幾次,只要命中一次,就把他作為單獨的模塊
},
// 公共的模塊
common: {
name: 'common', // chunk 名稱
priority: 0, // 優(yōu)先級
minSize: 0, // 公共模塊的大小限制
minChunks: 2 // 公共模塊最少復(fù)用過幾次,引用兩次及以上,把公共模塊拆分
}
}
}
}
2. 按需配置入口文件的chunk
多入口時,每個入口文件可以 按需配置自己所需要的chunk模塊:
- HtmlWebpackPlugin插件用于生成html文件
- 在 HtmlWebpackPlugin插件 的chunks屬性中配置當(dāng)前html需要引入的chunk
[webpack.common.js]
plugins: [
// 多入口 - 生成 index.html
new HtmlWebpackPlugin({
template: path.join(srcPath, 'index.html'),
filename: 'index.html',
// chunks 表示該頁面要引用哪些 chunk (即上面的 index 和 other),默認全部引用
chunks: ['index', 'vendor', 'common'] // 要考慮代碼分割
}),
// 多入口 - 生成 other.html
new HtmlWebpackPlugin({
template: path.join(srcPath, 'other.html'),
filename: 'other.html',
chunks: ['other', 'common'] // 考慮代碼分割
})
]
3. 抽離后打包產(chǎn)出
執(zhí)行npm run build
打包后dist文件中:
- index.html引入文件 變?yōu)関endor.js common.js index.js;
- other.html引入文件 變?yōu)閏ommon.js other.js
綜上,公共模塊和第三方模塊進行了獨立的分包打包并用作為緩存,避免了重復(fù)打包;同時多入口又可以按需引用自己所需模塊,避免引用無用包,提升了打包性能;