Webpack生产构建报错:UglifyJs与query-string交互问题求助
Hey there, let's tackle this frustrating UglifyJs error that's stopping your production build. The "Invalid assignment" error points directly to a syntax incompatibility between query-string and the older UglifyJs plugin you're using. Here are actionable steps to fix this:
1. Understand the Root Cause
Your current setup excludes node_modules from Babel transpilation, but newer versions of query-string (v6+) use ES6+ syntax that the built-in webpack.optimize.UglifyJsPlugin (which only supports ES5) can't parse. This mismatch is causing the invalid assignment error at line 8 of query-string/index.js.
2. Fix Options to Try
Option A: Transpile query-string with Babel
Modify your Babel loader rule to include query-string in transpilation while excluding other node_modules (to keep build times fast):
{ test: /\.(js|jsx)$/, exclude: /node_modules(?!\/query-string)/, // Exclude all node_modules except query-string use: { loader: 'babel-loader', options: { cacheDirectory: true, presets: ['react', 'env'], plugins: ['transform-object-rest-spread'] } } }
Option B: Upgrade to an ES6-compatible UglifyJs Plugin
The built-in UglifyJs plugin in Webpack 3 doesn't support ES6. Replace it with uglifyjs-webpack-plugin v1.x (compatible with Webpack 3):
- Install the plugin:
npm install uglifyjs-webpack-plugin@1 --save-dev - Update your Webpack config:
// Add this at the top const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); // Replace the built-in UglifyJsPlugin in your plugins array plugins: [ new webpack.HotModuleReplacementPlugin(), new UglifyJsPlugin({ sourceMap: true, uglifyOptions: { ecma: 6 // Enable ES6 parsing } }), // ... rest of your plugins ]
Option C: Downgrade query-string to an ES5-compatible version
If you prefer not to modify your Webpack/Babel config, downgrade query-string to v5.x (which is written in ES5):
npm install query-string@5 --save
Option D: Refine your Babel preset-env configuration
Your current babel-preset-env doesn't specify target environments, which might be leaving some ES6 syntax untranspiled. Update the preset to ensure full ES5 compatibility:
presets: [ 'react', ['env', { targets: { browsers: ['last 2 versions', 'ie >= 11'] }, modules: false // Let Webpack handle module bundling for better tree-shaking }] ],
3. Post-Fix Verification
After trying any of the above steps:
- Delete
node_modulesandpackage-lock.json - Run
npm installto fresh-install dependencies - Run your build command again:
npm run build
If the error persists, check line 8 of node_modules/query-string/index.js to confirm what syntax is causing the issue—this will help narrow down whether transpilation is working correctly.
内容的提问来源于stack exchange,提问作者LPS

