Remove console.logs with Webpack & Uglify

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: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        sourceMap: true, // Must be set to true if using source-maps in production
        terserOptions: {
          compress: {
            drop_console: true,
          },
        },
      }),
    ],
  },
};

Leave a Comment