Webpack集成UglifyJSPlugin报错:Cannot read property 'push' of undefined求助
Hey there, sorry you've been stuck on this for two days—let's break down the most likely causes and fix this issue step by step!
Common Causes & Solutions
1. Missing or Misconfigured plugins Array
The error "Cannot read property 'push' of undefined" almost always means Webpack can't locate the plugins array in your config. This happens if:
- You forgot to declare the
pluginsproperty entirely in yourwebpack.config.js - You misspelled it (e.g.,
plugininstead ofplugins)
Fix:
Ensure your config includes a properly initialized plugins array:
module.exports = { // Your other config entries (entry, output, module, etc.) plugins: [] // This array must exist, even if empty initially };
Then add your UglifyJSPlugin instance directly inside this array.
2. Version Incompatibility Between Webpack & UglifyJSPlugin
If you're using Webpack 4 or later, the old uglifyjs-webpack-plugin is no longer the recommended tool—Webpack 4+ includes built-in minification via terser-webpack-plugin (which handles ES6+ code far better than UglifyJS). Mismatched plugin and Webpack versions often throw unexpected errors like this.
Option A: Switch to Terser (Recommended)
- Install the plugin:
npm install terser-webpack-plugin --save-dev - Update your config to use it in the
optimizationsection (notplugins):const TerserPlugin = require('terser-webpack-plugin'); module.exports = { // Other config... optimization: { minimizer: [new TerserPlugin()] } };
Option B: Use a Compatible UglifyJSPlugin Version
If you need to stick with UglifyJSPlugin, install a version that matches your Webpack setup:
- For Webpack 4: Install
uglifyjs-webpack-plugin@^1.3.0or^2.2.0 - For Webpack 3 or earlier: Use
uglifyjs-webpack-plugin@^1.0.0
Then configure it correctly in the plugins array:
const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); module.exports = { // Other config... plugins: [ new UglifyJSPlugin({ // Optional config: compress, mangle, sourceMap, etc. compress: { warnings: false } }) ] };
3. Typos or Incorrect Plugin Initialization
Double-check that you're:
- Correctly requiring the plugin (no typos in the package name)
- Using the
newkeyword to instantiate the plugin (forgettingnewcan cause odd, hard-to-debug errors)
Next Steps If Issues Persist
If you still run into problems, share your full webpack.config.js code—small typos or missing config sections are easy to overlook, and seeing the complete file will help pinpoint the exact issue.
内容的提问来源于stack exchange,提问作者Randall

