问题
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.
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;
},
}),
}]
}
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?
回答1:
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));
}
}
}
}
}
}
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.
For more Webpack 4 related info/config you can review this webpack-demo project.
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');
}
}
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.
回答2:
Or:
splitChunks: {
cacheGroups: {
// We want all vendor (node_modules) to go into a chunk.
vendors: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
// Exclude preview dependencies going into vendors.
// Currently undocument feature: https://github.com/webpack/webpack/pull/6791
chunks: chunk => chunk.name !== "preview"
}
}
}
来源:https://stackoverflow.com/questions/49298706/how-to-code-split-one-of-two-entries-in-webpack-4