I'm trying to migrate to webpack4 from 3 and I'm having a really hard time migrating CommonsChunkPlugin
.
On WP3, I have the following simplified configuration:
const entries = {
client: './src/index.js',
common1: ['lodash'],
common2: ['react', 'react-dom']
};
module.exports = {
...
entry: entries,
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ['common1', 'common2'],
minChunks: Infinity
})
]
};
On WP4 I've already tried multiple combinations using optimization.splitChunks but I just can't get it to properly bundle my modules in a way that they are sharing common dependencies, like it used to be on WP3.
Here is what I used on my last try, but the final bundles are much bigger in size:
// same entries object
const entries = { ... };
module.exports = {
...
entry: entries,
optimization: {
splitChunks: {
minChunks: Infinity,
chunks: 'initial',
cacheGroups: {
common1: { test: 'common1' },
common2: { test: 'common2' },
// disables the default definition of these cache groups
vendors: false,
default: false
}
}
};
You can simply set
enforce = true
and this will "force" webpack to always create chunks for the cache group.If you're doing code splitting (using
import()
) then you'll want to setchunks = "all"
, because with"initial"
you're only grouping sync modules.And finally, if the groups "common1" and "common2" are likely to share any modules, you might consider giving one cache group a higher priority over the other, for example if "common1" is likely to be loaded first, this should have a higher priority so that "common2" does not need to be downloaded as a dependency.
Some useful links to helpfully demystify this stuff: