什么是splitChunks
- webpack4.x使用SplitChunksPlugin插件代替CommonsChunkPlugin
- 自动分割第三方模块和公共模块
- cacheGroups其实是splitChunks里面最核心的配置
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
mode: "development",
devtool: false,
entry: {
page1: "./src/page1.js",
page2: "./src/page2.js",
page3: "./src/page3.js",
},
optimization: {
splitChunks: {
chunks: "all",
minSize: 0,
minChunks: 1,
maxAsyncRequests: 3,
maxInitialRequests: 5,
automaticNameDelimiter: "~",
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
},
default: {
minChunks: 2,
priority: -20,
},
},
},
runtimeChunk: true,
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
chunks: ["page1"],
filename: "page1.html",
}),
new HtmlWebpackPlugin({
template: "./src/index.html",
chunks: ["page2"],
filename: "page2.html",
}),
new HtmlWebpackPlugin({
template: "./src/index.html",
chunks: ["page3"],
filename: "page3.html",
}),
],
};
SplitChunksPlugin插件工作流程
-
- SplitChunksPlugi先尝试把
minChunks
规则的模块抽取到单独的Chunk
中
-
- 判断该Chunk是否满足
maxInitialRequests
配置项的要求
-
- 判断体积是否满足
minSize
的大小,如果小于minSize
则不分包,如果大于minSize
判断是否超过maxSize
,如果大于maxSize
则继续拆分成更小的包