使用Webpack&删除console.logs丑化 [英] Remove console.logs with Webpack & Uglify

查看:315
本文介绍了使用Webpack&删除console.logs丑化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Webpack的Uglify插件删除console.logs,但似乎Webpack附带的Uglify插件没有该选项,文档中未提及.

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.

我正在像这样从webpack初始化uglify:

I am initializing uglify from webpack like this:

new webpack.optimize.UglifyJsPlugin()

我的理解是,我可以使用独立的Uglify lib获取所有选项,但是我不知道哪个?

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

问题是drop_console无法正常工作.

推荐答案

使用UglifyJsPlugin我们可以处理注释,警告,控制台日志,但是删除其中的所有这些并不是一个好主意.开发模式.首先检查您是否正在为prod env or dev env运行webpack,如果它是prod env,则可以删除所有这些内容,如下所示:

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

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

UPDATE 2019 现在需要在Webpack v4中使用Terser插件来支持ES6 https://github.com/webpack-contrib/terser-webpack-plugin#终结者选项

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

这篇关于使用Webpack&删除console.logs丑化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆