升级至Webpack 4后SplitChunks配置导致打包体积过大,求解决方案
Hey there, I see your bundle size skyrocketed from ~300KB to 4MB after switching from Webpack 2's CommonsChunkPlugin to Webpack 4's splitChunks—let's break down what's going wrong and fix this.
The Core Issue
Your current Webpack 4 splitChunks setup has a critical flaw: the test property for each cache group is set to strings like 'vendor_backbone', which doesn't actually match any modules. Webpack can't tell which libraries belong to each group, so it's not splitting out your vendor code at all. On top of that, minimize: false means your code isn't being uglified or compressed—another huge contributor to the size spike.
Corrected Configuration
Let's adjust your optimization section to replicate your old CommonsChunkPlugin behavior properly, plus enable compression to shrink the bundle:
optimization: { splitChunks: { cacheGroups: { // Target libraries from your original 'vendor' entry vendor: { name: 'vendor', // Match specific modules via regex test: /[\\/]node_modules[\\/](jquery|moment|django)[\\/]|site_common\/js\/(share-button|kakaolink-web)|nativeAppUtils/, chunks: 'all', enforce: true }, // Target React-related libraries from your original 'vendor_react' entry vendor_react: { name: 'vendor_react', test: /[\\/]node_modules[\\/](react|react-dom|redux|react-redux|redux-thunk|react-router|react-router-redux|react-intl|normalizr|lodash|classnames|react-day-picker|redux-form|immutability-helper|semantic-ui-react)[\\/]|site_common\/utils\/fetch/, chunks: 'all', enforce: true } } }, noEmitOnErrors: true, // Enable minimization to compress code (critical for small bundle sizes) minimize: true, // Optional: Customize the minimizer for better control minimizer: [ new require('terser-webpack-plugin')({ terserOptions: { compress: { drop_console: true // Optional: Remove console logs in production } } }) ] }
Key Changes Explained
- Fixed
testPatterns: Each cache group now uses regex to explicitly match the libraries from your original entry blocks. This tells Webpack exactly which modules to split into separate vendor chunks. - Enabled
minimize: true: Webpack 4 uses TerserPlugin by default for minimization—this will compress your code drastically, bringing the size back in line with your Webpack 2 build. - Simplified Groups: I removed
vendor_backbonesince your original entry only hadvendorandvendor_react—add it back if you still need it, just use a regex matching its specific modules.
Bonus Tips
- Verify Your Entry: Ensure your
entrysection still includes your app code alongside vendor entries (if you're using explicit vendor entries). Alternatively, letsplitChunksauto-detect vendor modules fromnode_modulesif you prefer less manual control. - Analyze Your Bundle: Use
webpack-bundle-analyzerto visualize what's in your bundle—it helps spot unexpected large modules. Install it withnpm install webpack-bundle-analyzer --save-devand add it as a plugin to your config.
内容的提问来源于stack exchange,提问作者eugene

