如何编码拆分Webpack 4中的两个条目之一? [英] How to code split one of two entries in Webpack 4?
问题描述
我有一个看似非常简单的Webpack代码拆分设置,但在迁移到Webpack 4时遇到了麻烦。我有两个条目,分别是 main
和预览
。我想对 main
中的供应商模块做一个初始代码,分成一个供应商
块,但我想保留预览
作为单个块。
I’ve got a seemingly pretty straightforward Webpack code splitting setup that I’m having trouble migrating to Webpack 4. I have two entries, called main
and preview
. I want to do an initial code split into a vendor
chunk for the vendor modules in main
, but I want to keep preview
as a single chunk.
Webpack 3中工作配置的相关部分:
Relevant part of the working configuration in Webpack 3:
{
entry: {
main: './src/application.js',
preview: './src/preview.js',
},
plugins: [{
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
chunks: ['main'],
minChunks({context}) {
if (!context) {
return false;
}
const isNodeModule = context.indexOf('node_modules') !== -1;
return isNodeModule;
},
}),
}]
}
具体来说,使用 CommonsChunkPlugin中的
选项使我可以轻松完成自己需要做的事情。 Webpack 4的 chunks
属性 optimization.splitChunks
配置中是否有等效项?
Specifically, using the chunks
property in the CommonsChunkPlugin
options allows me to do what I need to do easily. Is there an equivalent in Webpack 4’s optimization.splitChunks
configuration?
推荐答案
以下Webpack 4配置仅将 main
模块供应商依赖项拆分为一个单独的块。 预览
的其他依赖项仍在该块内。
The following Webpack 4 config only splits main
module vendor dependencies into a separate chunk. Other dependencies for preview
remains within that chunk.
{
entry: {
main: './test/application.js',
preview: './test/preview.js'
},
optimization: {
splitChunks: {
cacheGroups: {
vendors: {
name: 'vendors',
chunks: 'all',
enforce: true,
priority: 1,
test(module, chunks) {
const name = module.nameForCondition && module.nameForCondition();
return chunks.some(chunk => chunk.name === 'main' && /node_modules/.test(name));
}
}
}
}
}
}
供应商捆绑包中包含共享的依赖项,除非我们将 preview
cacheGroup配置为更高的优先级以强制此处包含的所有依赖项都应保留在其中
Shared dependencies are included in the vendors bundle unless we configure the preview
cacheGroup with higher priority to enforce that all dependencies included here should remain inside this chunk.
有关Webpack 4的更多相关信息/配置,您可以查看 webpack-demo 项目。
For more Webpack 4 related info/config you can review this webpack-demo project.
为了强制将所有供应商依赖项从 main
并从 main
和 preview
块重用它们,您必须配置预览
cacheGroup为:
In order to enforce splitting all vendors dependencies from main
and reuse them from main
and preview
chunks you must configure the preview
cacheGroup as:
preview: {
name: 'preview',
chunks: 'all',
enforce: true,
priority: 0,
test(module, chunks) {
return chunks.some(chunk => chunk.name === 'preview');
}
}
请注意的cacheGroup预览
块的优先级低于供应商
的优先级,以确保所有 main
依赖项预览
中的依赖项也从预览
捆绑包中引用。
Note that the cacheGroup for preview
chunk has lower priority than the vendors
one to ensures that all main
dependencies which are also dependencies in preview
are also referenced from the preview
bundle.
这篇关于如何编码拆分Webpack 4中的两个条目之一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!