简体   繁体   English

使用UglifyJS插件进行Webpack优化会导致运行时错误

[英]Webpack optimize with UglifyJS plugin causes runtime error

I have an isomorphic React application that is bundled via webpack. 我有一个通过webpack捆绑的同构React应用程序。

I have 2 entry points corresponding to 2 bundled file outputs: vendors.js and app.js . 我有2个入口点对应2个捆绑文件输出: vendors.jsapp.js

When running the webpack-dev-server or when compiling without any optimization flags, everything works fine. 当运行webpack-dev-server或没有任何优化标志进行编译时,一切正常。 However, as soon as I try to use the Uglify plugin, the compiled output contains errors. 但是,只要我尝试使用Uglify插件,编译后的输出就会包含错误。

I have tried: 我试过了:

webpack -p
webpack -optimize-minimize

or in the config: 或者在配置中:

new webpack.optimize.UglifyJsPlugin({sourceMap:false})

But all result in the same runtime error (undefined variables). 但都会导致相同的运行时错误(未定义的变量)。

Is there anything obvious that could be causing this? 有什么明显可能导致这种情况吗? Is Uglify being over-zealous and removing something it shouldn't? Uglify是否过度热心并且删除了不应该的东西?

The problem was being caused by the Uglify mangler. 问题是由Uglify管道造成的。 Without knowing which variable rename was causing the problem, the solution was to turn off mangling entirely: 在不知道哪个变量重命名导致问题的情况下,解决方案是完全关闭重整:

new webpack.optimize.UglifyJsPlugin({
  sourceMap: false,
  mangle: false
})

This should be added as a Webpack Plugin to your config file, eg: 这应该作为Webpack插件添加到您的配置文件中,例如:

var config = {

  //... various config settings

  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: false,
      mangle: false
    })
  ]
};

For those who deactivated mangle and still have the issue, check if you build with -p parameter. 对于那些停用了mangle但仍有问题的人,请检查是否使用-p参数构建。 It appears -p also mangle the output, and in my case, I had to switch UflifyJsPlugin mangle to false and build without the -p flag to get it to work (at the cost of an increase of the weight of the js of around 50%) 它似乎-p也破坏了输出,在我的情况下,我不得不将UflifyJsPlugin mangle切换为false并且在没有-p标志的情况下构建以使其工作(代价是增加约50的js的重量) %)

I fixed this by using the following (I'm using Webpack 4.5): 我通过使用以下(我正在使用Webpack 4.5)修复此问题:

var config = {
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        uglifyOptions: {
          safari10: true,
          mangle: {
            safari10: true,
          }
        }
      })
    ]
  }
};

From https://github.com/mishoo/UglifyJS2/tree/harmony#mangle-options : 来自https://github.com/mishoo/UglifyJS2/tree/harmony#mangle-options

safari10 (default false) -- Pass true to work around the Safari 10 loop iterator bug "Cannot declare a let variable twice". safari10(默认为false) - 传递true以解决Safari 10循环迭代器错误“无法声明两次let变量”。 See also: the safari10 output option. 另请参见:safari10输出选项。

Also note that this goes in optimization.minimizer . 另请注意,这在optimization.minimizer It didn't work for me when I put it in plugins . 当我把它放在plugins时它对我不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM