Vue-cli项目执行npm build报错,如何修改build.js?
Hey there! Let's get that build error sorted out quickly. First, I think you meant npm run build instead of npm build (a tiny typo, no big deal 😄). The error is telling you that the old CommonsChunkPlugin was deprecated in Webpack 4+, and you need to use the newer optimization.splitChunks configuration instead. Here's exactly how to update your build configuration (usually build/webpack.prod.conf.js in Vue-CLI 2.x projects):
Step 1: Remove the Deprecated CommonsChunkPlugin Code
Open your build config file and locate the plugins array. Look for entries that look like this—delete them entirely:
// Remove these lines from the plugins array new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module) { return ( module.resource && /\.js$/.test(module.resource) && module.resource.indexOf(path.join(__dirname, '../node_modules')) === 0 ) } }), new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', chunks: ['vendor'] })
Step 2: Add the Modern optimization.splitChunks Configuration
Add a new optimization section to your Webpack config object. This replaces the old plugin's functionality with modern, built-in Webpack settings:
module.exports = { // ... keep all your existing config (entry, output, module rules, etc.) optimization: { splitChunks: { chunks: 'all', // Split all types of chunks (initial, async, lazy) cacheGroups: { vendor: { name: 'vendor', // Name of the output chunk for third-party libs test: /[\\/]node_modules[\\/]/, // Target all modules in node_modules priority: 10, // Process this group before others chunks: 'initial' // Only split initial (non-async) dependencies }, common: { name: 'common', // For shared code across your own components minChunks: 2, // Only split code used in at least 2 chunks priority: 5, reuseExistingChunk: true // Reuse existing chunks to avoid duplication } } }, runtimeChunk: { name: 'manifest' // Extract Webpack's runtime logic into a separate chunk } }, // ... your existing plugins array (now without the old CommonsChunkPlugin entries) }
What This Does
vendorchunk: Extracts all third-party libraries fromnode_modulesinto a separatevendor.jsfile, just like the old plugin did.commonchunk: Pulls reusable code from your own components intocommon.js, reducing duplicate code in your bundles.manifestchunk: Isolates Webpack's runtime logic, which prevents unnecessary changes tovendor.jsbetween builds (great for improving user-side caching).
For Vue-CLI 3+ Projects (No build.js File)
If your project uses Vue-CLI 3 or later, you won't have a build.js—instead, add this to your vue.config.js:
module.exports = { configureWebpack: { optimization: { splitChunks: { chunks: 'all' } } } }
Test It Out
Save your changes, then run npm run build again. The error should be gone, and you'll see your optimized chunks (vendor.js, manifest.js, etc.) in the dist folder just like before!
内容的提问来源于stack exchange,提问作者Free




