grunt-contrib-uglify 不解析 "let" 关键字吗?

Does grunt-contrib-uglify not parse "let" keywords?

我收到一个错误,

'Unexpected token: name (bazz)'

当我的 g运行t 任务是 运行ning uglify 时。 我在该行中唯一注意到的是我使用了 'let' 关键字而不是 'var',所以我不确定为什么会抛出该错误。

我有一个 if else 语句,每个语句中都有 let varName,即:

function foo (bar) {
    if (condition) {
        let bazz = fn();
        //doSomething with bazz
        _.assign(bar, bazz);
    } else {
        let bazz = fn2();
        //doSomething different with bazz
        _.assign(bar, bazz);
    }
}

我可以通过在 if else 子句之前添加 var bazz = {}; 来改变它,但我想避免这种情况,因为无论如何我都必须将 bazz 分配给 fn() 和 fn2()。

想知道是否有其他人 运行 了解此问题以及他们如何解决此问题。提前致谢!

在进一步研究这个主题后,我发现 grunt-contrib-uglify 和 gulp-uglify 都依赖 UglifyJS,但它还不支持 ES6 "Harmony"。关注 https://github.com/mishoo/UglifyJS2/issues/448 获取更新。

您还可以使用 grunt-babel 等工具将您的 ES6 代码编译为 ES5。

我在官方 gulp-uglify npm 页面上看到了以下内容。

注意推荐:

To help properly handle error conditions with Node streams, this project recommends the use of pump. For more information, see Why Use Pump?.

我上面页面的例子实现是:

gulpfile.js

var gulp = require('gulp');  
var pump = require('pump');  

// the npm page states:  
// can be a git checkout or another module 
// (such as `uglify-js-harmony` for ES6 support)
var uglifyjs = require('uglify-js-harmony');   
var minifier = require('gulp-uglify/minifier');  

var concat = require('gulp-concat');

gulp.task('compress', function (cb) {  
  // the 'options' argument is included in the example, 
  // but i don't know what it does or how it can be removed  
  var options = {  
    preserveComments: 'license'  
  };  

  pump([  
      gulp.src('my_scripts/*.js'),  // gets all js scripts in this folder  
      minifier(options, uglifyjs),  
      concat('my_bundled_script.js'), // concatenates all scripts into this file  
      gulp.dest('dist')  // puts the file into this folder
    ],cb 
  );  
});  

package.json

{
  "devDependencies": {
    "gulp": "latest",
    "pump": "latest",
    "gulp-concat": "latest",
    "gulp-uglify": "latest",
    "uglify-js-harmony": "latest"
  },
  "dependencies": {}
}

结果

不使用 uglify-js-harmony:

  • pump 有助于定位错误的来源(使用 gulp-uglify 时)
  • 具有 let 语句的文件导致错误

使用uglify-js-harmony时没有出现错误。

其他注意事项:

以上页面目前显示:

// can be a git checkout or another module  
// (such as `uglify-js-harmony` for ES6 support)
var uglifyjs = require('uglify-js');

但是在安装时 uglify-js-harmony 我收到了警告信息:

npm WARN deprecated uglify-js-harmony@2.7.7: deprecated in favour of uglify-es

但是,当我尝试使用 uglify-es 而不是 uglify-js-harmony 时,我收到一条错误消息,类似于此处记录的错误消息:

https://github.com/terinjokes/gulp-uglify/issues/287

我试图从那里关注问题线索,但迷路了,找不到关于如何实施 uglify-es 的明确解决方案。