Webpack 4: SplitChunks Optimization
It's 2018, and Webpack 4 ("Legato") has completely changed how we handle code splitting. The old CommonsChunkPlugin was confusing and often resulted in inefficient bundles. Its replacement, SplitChunksPlugin, is much more intelligent and works out of the box with mode: 'production'.
The Default Strategy
By default, Webpack 4 only splits chunks that are:
- Async (using
import()). - Larger than 30kb.
- Shared by 2 or more chunks.
Customizing the Vendor Bundle
To get the most out of long-term caching, we want to separate our stable node_modules into a separate vendors bundle.
// webpack.config.js
module.exports = {
optimization: {
splitChunks: {
chunks: 'all', // Include both async and initial chunks
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
};
Advanced: Grouping by Library
Sometimes you want specific libraries (like React or D3) in their own chunks because they change at different frequencies.
cacheGroups: {
reactVendor: {
test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
name: 'react-vendor',
chunks: 'all',
priority: 20, // Higher priority than the general vendor group
},
}
Why "all"?
In the past, we mostly split "initial" chunks. But in 2018, we're using dynamic imports everywhere. Setting chunks: 'all' tells Webpack that it can share modules between initial and on-demand chunks, reducing the total amount of code sent to the user.
Webpack 4 is a massive step toward "zero config," but mastering splitChunks is still what separates a good build from a great one.
Aunimeda builds modern web frontends - from single-page applications to complex multi-locale sites.
Contact us to discuss your frontend project. See also: Web Development, Corporate Website Development