从webpack v4开始,删除了CommonsChunkPlugin,而改为直接在config.optimization.splitChunks配置来抽取公共模块。
关于压缩配置。
module.exports = {
//...
optimization: {
splitChunks: {
chunks: 'async',
minSize: 30000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
automaticNameMaxLength: 30,
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
}
};
splitChunks
splitChunks下的所有配置,除cacheGroups 以外都可以被cacheGroups中的缓存组继承。
chunks
function (chunk) | string
这表明将选择哪些块进行优化。当提供一个字符串,有效值为all
,async
和initial
。提供all
可能特别强大,因为它意味着即使在异步和非异步块之间也可以共享块。
默认为 async
即,只抽取异步加载的模块。
all
抽取所有
initial
只对入口使用的模块进行抽取,☺
minSize
Minimum size, in bytes, for a chunk to be generated.
生成块的最小的大小,
即一个模块它的大小超过了这个值,才会被抽离出来,
minChunks
Minimum number of chunks that must share a module before splitting.
模块在分割之前被共享的的次数?
一个模块被其他模块引用的次数,如果超过这个设置次数,就会被提取为公共模块。
maxAsyncRequests
Maximum number of parallel requests when on-demand loading.
按需加载并行请求的最大数量。
maxInitialRequests
Maximum number of parallel requests at an entry point.
入口点并行请求的最大数量
automaticNameDelimiter
By default webpack will generate names using origin and name of the chunk (e.g. vendors~main.js). This option lets you specify the delimiter to use for the generated names.
默认情况下,webpack会使用块的来源和名称生成名称(例如vendor〜main.js)。 此选项使您可以指定用于生成名称的定界符。
automaticNameMaxLength
Allows setting a maximum character count for chunk names that are generated by the SplitChunksPlugin
允许为SplitChunksPlugin生成的块名称的长度的最大字符数
cacheGroups
缓存组,默认情况下有两个缓存组,
- 第一个缓存组会把node_modules中的模块全部提取到一块,
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
-
第二个缓存组,则处理其余的模块,
规则是, 如果一个模块,被引用超过两次就会被分离出来。
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
每个缓存组未指定的配置默认会继承optimization.splitChunks的配置。
也可以自定义缓存组。
例如:
如果x.js 被引用超过三次,就会被分离出来
my: {
test: /\x.js/,
minChunks: 3,
},