优化Webpack打包时产生的错误uglifyjs / terser

在学习webpack优化打包时,发生的打包错误。使用uglifyjs-webpack-plugin或terser-webpack-plugin插件优化打包,都会报这样的错误。

vue.config.js配置

const { defineConfig } = require('@vue/cli-service')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin');

module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: {
      '/api': {
        target: 'https://127.0.0.1:3000/', 
        ws: true,
        changeOrigin: true, 
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  },
  // TerserPlugin 
  // configureWebpack: {
  //   optimization: {
  //     minimizer: [
  //       new TerserPlugin({
  //         terserOptions: {
  //           compress: {
  //             warnings: false,
  //             drop_console: true,
  //             drop_debugger: true,
  //             pure_funcs: ["console.log"]
  //           }
  //         }
  //       })
  //     ],
  //   },
  // }
 // UglifyJsPlugin
  configureWebpack: config => {
    // 生产环境
    if (process.env.NODE_ENV == 'production') {
      // 压缩代码
      config.plugins.push(
        new UglifyJsPlugin({
          uglifyOptions: {
            warnings: false, // 不显示警告信息
            compress: {
              // warnings: false, // 打包错误,则注释这一行
              drop_debugger: true, // 删除debug
              drop_console: true, // 移除console.* 、log=console.log
              pure_funcs: ['console.log']
            }
          },
          sourceMap: false, // 缩小打包体积
          parallel: true, // 使用多进程压缩
          cache: true, // 启用缓存
          extractComments: true, // 抽离注释,单独抽出成一个文件 [name].[hash].[ext].LICENSE
        })
      )
    }
  }

})

直接执行打包Webpack命令,是没有问题,就是配置vue.config.js之后,不行了。

# webpack打包
npm run build

当然,也找到一些方案,说是webpack版本与插件版本不对应产生的。

// ...
webpack 5.x 匹配terser-webpack-plugin 5.x
webpack 4.x 匹配terser-webpack-plugin 4.x

找了半天暂时还没有解决,大家有什么好的解决方案吗?欢迎留言!

猜你喜欢

转载自blog.csdn.net/qq_58062502/article/details/130161711