Remove console.logs with Webpack & Uglify

Mladen Petrovic picture Mladen Petrovic · Dec 8, 2016 · Viewed 63k times · Source

I am trying to remove console.logs with Webpack's Uglify plugin but it seems that Uglify plugin that comes bundled with Webpack doesn't have that option, its not mentioned in the documentation.

I am initializing uglify from webpack like this:

new webpack.optimize.UglifyJsPlugin()

My understanding is that I can use standalone Uglify lib to get all the options, but I don't know which one?

The problem is that drop_console isn't working.

Answer

Mayank Shukla picture Mayank Shukla · Dec 8, 2016

With UglifyJsPlugin we can handle comments, warnings, console logs but it will not be a good idea to remove all these in development mode. First check whether you are running webpack for prod env or dev env, if it is prod env then you can remove all these, like this:

var debug = process.env.NODE_ENV !== "production";

plugins: !debug ? [
   new webpack.optimize.UglifyJsPlugin({

     // Eliminate comments
        comments: false,

    // Compression specific options
       compress: {
         // remove warnings
            warnings: false,

         // Drop console statements
            drop_console: true
       },
    })
]
: []

Reference: https://github.com/mishoo/UglifyJS2#compressor-options

UPDATE 2019 Need to use terser plugin now for ES6 support in webpack v4 https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions

webpack.config.js

module.exports = {
  optimization: {
    minimizer: [
      new TerserPlugin({
        sourceMap: true, // Must be set to true if using source-maps in production
        terserOptions: {
          compress: {
            drop_console: true,
          },
        },
      }),
    ],
  },
};