利用 terser-webpack-plugin 去除生产包中的console

前言

一般我们在开发中大多数会使用 console.log 去打印一些数据, 以便于开发调试。到了生产中这些 console.log 就显得有点多余,且容易暴露一些重要信息。所以我们在发生产的时候有必要将 console.log 等打印信息给去除。 我们可以使用 webpack 去帮助我们实现这个效果,免去了手动删除这种繁琐的操作。

terser-webpack-plugin

从webpack官网上发现官网推荐使用的TerserWebpackPlugin大致能满足我们的需求。 需要注意的是 webpack4 要安装 terser-webpack-plugin@4 的版本。

  1. 安装依赖
npm install terser-webpack-plugin --save-dev
  1. 引入插件
const TerserPlugin = require('terser-webpack-plugin')
  1. 配置
optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: false, // 默认false,设置为true, 则会删除所有console.* 相关的代码。
            pure_funcs: ["console.log"], // 单纯禁用console.log
          }
        }
      })
    ]
  }

附上一段关于 drop_consolepure_funcs 属性的说明

drop_console (default: false) – Pass true to discard calls to console.* functions. If you wish to drop a specific function call such as console.info and/or retain side effects from function arguments after dropping the function call then use pure_funcs instead.

pure_funcs (default: null) – You can pass an array of names and Terser will assume that those functions do not produce side effects. DANGER: will not check if the name is redefined in scope. An example case here, for instance var q = Math.floor(a/b). If variable q is not used elsewhere, Terser will drop it, but will still keep the Math.floor(a/b), not knowing what it does. You can pass pure_funcs: [ ‘Math.floor’ ] to let it know that this function won’t produce any side effect, in which case the whole statement would get discarded. The current implementation adds some overhead (compression will be slower).

小伙伴可点击这里自行查看terserOptions更多配置

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值