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

南门鸿振
2023-12-01

前言

一般我们在开发中大多数会使用 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更多配置

 类似资料: