UglifyJS webpack plugin throws: Unexpected token:

2020-07-17 16:29发布

问题:

I used to have problems with UglifyJS for Webpack and ES6 modules:

ERROR in static/js/vendor.6ccd9e38979a78765c7a.js from UglifyJs Unexpected token: name (features) [./node_modules/pica/lib/mathlib.js:19,0][static/js/vendor.6ccd9e38979a78765c7a.js:39003,6]

I read that the new beta version of the Webpack plugin supports ES6:

https://github.com/webpack-contrib/uglifyjs-webpack-plugin

new webpack.optimize.UglifyJsPlugin({
  uglifyOptions: {
    ie8: false,
    ecma: 8, // I also tried 7 and 6
    parse: {},
    mangle: {
      properties: {
        // mangle property options
      }
    },
    output: {
      comments: false,
      beautify: false
    },
    compress: {},
    warnings: true
  }
}),

However, now I get another error:

ERROR in static/js/vendor.6ccd9e38979a78765c7a.js from UglifyJs Unexpected token: name (features) [static/js/vendor.6ccd9e38979a78765c7a.js:39003,6]

What could be the problem?

回答1:

You can try installing babel-preset-env and adding presets": [ "env" ] to your webpack.config.js or babelrc.

Uglify cannot parse ES6 on its own( as far as I know), so you need to transpile your code down to ES5, post-processing your generated JS with babel, or use a different minifier. My recommendation is Babelify to which I switched after having constant errors with Uglify.

Edit: The problem might be in your new webpack.optimize.UglifyJsPlugin declaration, There are problems with using this declaration with Webpack 3+. You need to import the uglifyjs-webpack-plugin and change plugin declaration to new UglifyJSPlugin(example). Here is a reference.

Example:

const UglifyJSPlugin = require('uglifyjs-webpack-plugin')

    const config = {
      ...
      plugins: [
        new UglifyJSPlugin({ uglifyOptions: { ...options } })
      ]
    }