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 2019Need to use terser plugin now for ES6 support in webpack v4https://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, }, }, }), ], },};
Try drop_console:
plugins: [ new Webpack.optimize.UglifyJsPlugin({ compress: { drop_console: true, } }]
Update: For webpack v4 it has changed a little:
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');...optimization: { minimizer: [ new UglifyJSPlugin({ uglifyOptions: { compress: { drop_console: true, } } }) ]}
I personally think console logs (especially console.error
) are very useful on prod and think it's a good idea to keep them. If you really want to drop specific console functions such as just console.log
you should use pure_funcs
option e.g. pure_funcs: ['console.log']
and this will drop console.log
since pure functions do not produce side effects then Uglify can discard ones not assigned to anything.
optimization: { minimizer: [ new UglifyJSPlugin({ uglifyOptions: { compress: { // Drop only console.logs but leave others pure_funcs: ['console.log'], }, mangle: { // Note: I'm not certain this is needed. reserved: ['console.log'] } } }) ]}
For TerserJS (Uglify is deprecated and does not support new JS features you should NOT use it)
optimization: { minimizer: [ new TerserPlugin({ terserOptions: { compress: { drop_console: true } } }) ]}
As discussed you can also use pure_funcs
alternatively.