一、前言:

上一个插件里边提到这个插件,然后看了一下发现一直在维护,而上一个插件已经不维护了,故尝试。

上一篇文章地址: https://blog.csdn.net/sinat_32017511/article/details/115764005

二、安装插件:

安装插件  terser-webpack-plugin

yarn add -D terser-webpack-plugin  或  npm install terser-webpack-plugin

三、在 vue.config.js 文件中进行配置

1.在头部引入

const TerserPlugin = require("terser-webpack-plugin");

2.配置这段代码

new TerserPlugin({
      terserOptions: {
      ecma: undefined,
      warnings: false,
      parse: {},
      compress: {
        drop_console: true,
        drop_debugger: false,
        pure_funcs: ['console.log'], // 移除console
      },
    },
}),

为了避免不明确,复制完整代码段:

//打包配置自动忽略console.log等
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
 
module.exports = {
	publicPath: './',
	devServer: {
		......
	},
	css:{
		......
	},
	// eslint-disable-next-line no-unused-vars
	configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
          return {
            plugins: [
              //打包环境去掉console.log
             new TerserPlugin({
              terserOptions: {
              ecma: undefined,
              warnings: false,
              parse: {},
              compress: {
                drop_console: true,
                drop_debugger: false,
                pure_funcs: ['console.log'], // 移除console
              },
            },
         }),
       ],
     }
   }
 }
}

但是这里如果你使用了最新版的  terser-webpack-plugin ,则会产生一个 ‘JavaScript’ 错误。

所以这里使用版本 "terser-webpack-plugin": "^4.2.3"

yarn add -D terser-webpack-plugin@4.2.3

在webpack4 里边确实需要 配置这个 terser-webpack-plugin 插件,在 webpack5 中已经默认配置好了(具体可以去看文档),所以,期待脚手架配置 webpack5 上线。

但是,问题又来了

我使用这个版本去做打包的时候,确实可以打包成功,但是打包的时候超级卡,超级慢,无奈,我换回了上一个插件,毕竟我的需求就是想要干掉 console 。

 

找到解决办法,来堵坑:

上面提到了用最新版的 terser-webpack-plugin 会报错,于是我按照网上资料查找使用了 4.2.3 版本,但是打包很慢,然后后来经过查找,发现我可能没有开多进程,开了之后一路顺风。

new TerserPlugin({
    cache: true,
	sourceMap: false,
	// 多进程
	parallel: true,
	terserOptions: {
	    ecma: undefined,
	    warnings: false,
		parse: {},
		compress: {
			drop_console: true,
			drop_debugger: false,
			pure_funcs: ['console.log'], // 移除console
		},
	},
}),

 

 

Logo

前往低代码交流专区

更多推荐