关于webpack打包插件uglifyjs-webpack-plugin报错

项目进行打包优化,配置了打包环境,代码如下:

const UglifyJsPlugin = require(uglifyjs-webpack-plugin)
configureWebpack: (config) => {
          
   
    if (isProd) {
          
   
      const plugins = []
      plugins.push(
        new UglifyJsPlugin ({
          
   
          sourceMap: false,
          // 多进程
          parallel: true,
          uglifyOptions: {
          
   
            warnings: false,
            compress: {
          
   
              drop_console: false,
              drop_debugger: false
            }
          },
        })
      );
      config.plugins = [...config.plugins, ...plugins]
    }
  }

但是打包发现报错

-  Building for production...

 ERROR  Failed to compile with 1 errors                                                                        9:36:08

 error

static/js/vendors~app.042c0081.js from UglifyJs
undefined

 ERROR  Build failed with errors.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! cli4@0.1.0 build:prod: `vue-cli-service build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cli4@0.1.0 build:prod script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:Users14581AppDataRoaming
pm-cache\_logs2020-09-10T01_36_08_213Z-debug.log

这里的

error

static/js/vendors~app.042c0081.js from UglifyJs
undefined

类似这种报错,是因为最新版的uglifyjs-webpack-plugin插件已经不支持es6语法(https://github.com/webpack-contrib/uglifyjs-webpack-plugin/blob/master/CHANGELOG.md#200-2018-09-14)

解决方法

用插件terser-webpack-plugin代替uglifyjs-webpack-plugin

配上terser-webpack-plugin:用法

const TerserPlugin = require(terser-webpack-plugin)
configureWebpack: (config) => {
          
   
    if (isProd) {
          
   
      const plugins = []
      plugins.push(
        new TerserPlugin({
          
   
          cache: true,
          sourceMap: false,
          // 多进程
          parallel: true,
          terserOptions: {
          
   
            warnings: false,
            compress: {
          
   
              drop_console: false,
              drop_debugger: false
            }
          },
        })
      );
      config.plugins = [...config.plugins, ...plugins]
    }
  }
经验分享 程序员 微信小程序 职场和发展