防止 gulp uglify 剥离 es6

Prevent gulp uglify from stripping out es6

我正在使用 gulp babel 编译 es6,但 uglify 似乎完全剥离了我的 es6。运行时,我的命令行中没有出现任何错误。知道为什么要删除它吗?

我的 gulp 任务如下所示:

gulp.task('scripts', function () {
  return gulp.src('src/js/*.js')
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('dist/js'));
});

我的javascript:

document.addEventListener('DOMContentLoaded', function (event) {
  console.log('ready to es6!');
  const foo = 4;
});

输出,compiled/uglified javascript:

"use strict";document.addEventListener("DOMContentLoaded",function(e){console.log("ready to es6!")});
//# sourceMappingURL=scripts.js.map

注意 const foo = 4 被遗漏了。删除 .pipe(babel()) 会导致 const 得到正确编译。

如果有帮助,devDependencies:

"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/preset-env": "^7.2.3",
"browser-sync": "^2.26.3",
"gulp": "^3.9.1",
"gulp-babel": "^8.0.0-beta.2",
"gulp-sass": "^4.0.2",
"gulp-sourcemaps": "^2.6.4",
"gulp-uglify": "^3.0.1",
"node-sass": "^4.11.0"
}

UglifyJS(gulp-uglify 的依赖项)有一个压缩选项,默认情况下会删除未使用的变量。由于您从未引用 foo 它已从压缩源中删除。

来自UglifyJS2 docs

Compress options: unused (default: true) -- drop unreferenced functions and variables (simple direct variable assignments do not count as references unless set to "keep_assign")

由于 const foo = 4 是一个简单的直接变量赋值,它不会出现在您的压缩代码中。您可以假设您不需要未使用的代码或调整您的 gulp 文件:

gulp.task('scripts', function () {
  return gulp.src('src/js/*.js')
  .pipe(sourcemaps.init())
  .pipe(babel())
  .pipe(uglify({
     compress: {
       unused: false
     }
   }))
  .pipe(sourcemaps.write('./'))
  .pipe(gulp.dest('dist/js'));
});