使用 TerserWebpackPlugin 删除 console.log

Isa*_*edo 8 webpack

我有一个4.23.1版的 Webpack,并使用 TerserWebpackPlugin 来缩小我的项目。我想在生产中删除 console.log,但它不起作用。我尝试了 UglifyJsplugin,但都没有。

这是我的webpack.config.js文件:

var path = require('path')
var webpack = require('webpack')
const bundleOutputDir = './wwwroot/dist';
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const configs = require('./wwwroot/js/config')
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  mode: 'production',
  optimization:{
    minimizer:[
      new TerserPlugin({
        terserOptions:{
          cache: true,
          parallel: true,
          sourceMap: false,
          compress:{
            drop_console: true,          
          }           
        }
      })
    ]
  },
  context: __dirname,
  entry: {
    main: ['babel-polyfill', './App/index.js']
  },
  plugins:[
    new VueLoaderPlugin(),
    new webpack.DefinePlugin({
      'SERVICE_URL': JSON.stringify(configs.url),
    }),        
  ],
  module: {
    rules: [...]
  },
  resolve: {...},
  devServer: {
    historyApiFallback: true,
    noInfo: false,
    overlay: true
  },
  performance: {
    hints: false
  },
  output: {
    path: path.join(__dirname, bundleOutputDir),
    filename: '[name].js',
    publicPath: 'dist/'
  },
  devtool: '#eval-source-map'
}
Run Code Online (Sandbox Code Playgroud)

pun*_*bit 6

好问题,因为这并不像看起来那么简单!我个人之前也遇到过类似的问题,即使使用了与您类似的配置,控制台仍然存在。考虑到您的配置,我会说它应该输出正确的non-console.logs输出!为什么会失败?我建议查看以下线程https://github.com/webpack-contrib/terser-webpack-plugin/issues/57

以下答案使用以下软件包:

  • 网络包 4.41.6
  • terser-webpack-plugin 2.3.5

我的回答遵循原始terser插件中记录的压缩选项,可以在 URL https://github.com/terser/terser 中找到

为简单起见,假设有一个基本配置文件,沿着不影响输出的答案合并。所以,这是一个工作示例:

const merge = require('webpack-merge')
const webpackCommonConfig = require('./webpack.common.js')
const TerserPlugin = require('terser-webpack-plugin')

module.exports = merge(webpackCommonConfig, {
  mode: 'production',
  optimization: {
    minimizer: [
      new TerserPlugin({
        terserOptions: {
           compress: {
               drop_console: true
           }
          }
      })
    ]
  }
})
Run Code Online (Sandbox Code Playgroud)