我如何在 webpack 4 中指定不将某个模块打入chunk?比如我不想让lodash被打入vendor文件(无论后果如何),我该怎么做?
这是当前的配置:
splitChunks: {
name: 'vendors',
maxAsyncRequests: 1,
maxInitialRequests: 2,
chunks: 'initial',
}
我如何在 webpack 4 中指定不将某个模块打入chunk?比如我不想让lodash被打入vendor文件(无论后果如何),我该怎么做?
这是当前的配置:
splitChunks: {
name: 'vendors',
maxAsyncRequests: 1,
maxInitialRequests: 2,
chunks: 'initial',
}
一个测试
也可以使用方法。这样可以提供很大的灵活性。例如...
vendor: {
test(mod/* , chunk */) {
// Only node_modules are needed
if (!mod.context.includes('node_modules')) {
return false;
}
// But not node modules that contain these key words in the path
if ([ 'lodash', 'react'].some(str => mod.context.includes(str))) {
return false;
}
return true;
},
name: 'vendor',
chunks: 'all',
reuseExistingChunk: true
},
test: /[\\/]node_modules[\\/]((?!(lodash)).*)[\\/]/
webpack.config.js
module.exports = {
//...
optimization: {
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/](!lodash)[\\/]/,
name: 'vendor',
chunks: 'all',
}
}
}
}
};
从 /node_modules
加载项目所有依赖项到名为 vendors
的块的配置如下:
optimization: {
splitChunks: {
cacheGroups: {
commons: { test: /[\\/]node_modules[\\/]/, name: "vendors", chunks: "all" }
}
}
}
optimization.splitChunks
的文档仍然相当稀少,所以我希望这至少能帮助您指明正确的方向。test: /[\\/]node_modules[\\/](?!lodash)(.[a-zA-Z0-9.\-_]+)[\\/]/
它对我有效
undefined
,所以我在你的解决方案中添加了一个条件if (module.context) {...}
来包围代码,并在该条件之外添加了一个return false
语句,以便不包括那些没有上下文的模块。 - Giorgio Tempesta