1. 背景
背景:我们有一个函数有两个场景都需要调用它,暂且可理解为点击两个不同作用的按钮都会调用它吧,伪代码如下:
handleClick = (item, type) => {
if(type === 1) {
this.func1(item.id) }
else {
this.func2()
}
}后面有同事改这个函数时,加了一句看似不会出啥事的废代码:
handleClick = (item, type) => {
console.log(item.id) // 这句是新加的 if(type === 1) {
this.func1(item.id) }
else {
this.func2()
}
}嗯~小程序发布后,突然有人反馈这个按钮点击没反应了,本地测试发现点击时,console.log报错了。
于是,萌生了在生产环境去除console.log的优化想法,
2. 解决办法
(1)使用 uglifyjs-webpack-plugin
使用最新版的安装包会报“warning is not a supported option”的错误,把版本降到1.1.1后就可以正常使用了
(2)使用 terser-webpack-plugin
这个插件可以正常使用。
3. 代码展示
我按taro的语法使用该插件时,一直报参数设置格式错误,后来采用的是taro 里面的webpackChain ,它的使用跟webpack-chain类似,感兴趣的可自行查阅相关资料,代码如下:
备注:这里有两个需要注意的地方,(1)use的第一个参数是插件,这里直接使用,不需要new,(2)use的第二个参数是个数组,即便只有一个参数,也要写成数组的形式。
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
webpackChain(chain, webpack){
chain.plugin('uglifyjs-webpack-plugin')
.use(UglifyJsPlugin, [{
uglifyOptions: {
compress: {
warnings: false,
drop_console: true,//console
pure_funcs: ['console.log']//移除console
}
}
}])
}const TerserPlugin = require('terser-webpack-plugin');
webpackChain(chain, webpack){
chain.plugin('terser-webpack-plugin')
.use(TerserPlugin, [{
terserOptions: {
ecma: undefined,
warnings: false,
parse: {},
compress: {
drop_console: true,
drop_debugger: false,
pure_funcs: ['console.log'] // 移除console
}
}}])
}3. 参考文章
1. webpack.js.org/plugins/ugl…