Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove console.log with TerserWebpackPlugin

Tags:

webpack

I have a version 4.23.1 of Webpack and use TerserWebpackPlugin to minify my project. I want to drop console.log on production, but it doesn't work. I tried UglifyJsplugin and neither.

This is my webpack.config.js file:

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'
}
like image 301
Isaías Orozco Toledo Avatar asked Feb 06 '19 19:02

Isaías Orozco Toledo


1 Answers

Good question, as this is not as trivial as it seems! I've personally faced a similar issue before, where the console persisted, even though used a similar configuration as yours. Considering your configuration, I'd say it should output the correct non-console.logs output! Why does it fail? Id' suggest looking into the following thread https://github.com/webpack-contrib/terser-webpack-plugin/issues/57

The following answer uses the following packages:

  • webpack 4.41.6
  • terser-webpack-plugin 2.3.5

My answer follows the compress options documented in the original terser plugin that can be found in the URL https://github.com/terser/terser

For the sake of simplicity assume there's a base configuration file, merged along the answer that doesn't affect the output. So, here's a working example:

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
          }
        }
      })
    ]
  }
})

like image 54
punkbit Avatar answered Oct 31 '22 23:10

punkbit