Remove console.logs with Webpack & Uglify

前端 未结 8 1435
谎友^
谎友^ 2020-11-28 23:59

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

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 00:10

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

提交回复
热议问题