javascriptgulpgulp-uglifygulp-babel

Prevent gulp uglify from stripping out es6


I'm using gulp babel to compile es6, but it seems like uglify is stripping out my es6 altogether. I'm not getting any errors in my command line when this runs. Any ideas why this is getting stripped out?

My gulp task looks like this:

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'));
});

My javascript:

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

The outputted, compiled/uglified javascript:

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

Notice the const foo = 4 is left out. Removing the .pipe(babel()) results in the const getting compiled properly.

If it's helpful, 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"
}

Solution

  • UglifyJS (a dependency of gulp-uglify) has a Compress option that by default removes unused vars. Since you never reference foo it is removed from the compressed source.

    From 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")

    Since const foo = 4 is a simple direct variable assignment it doesn't appear in your compressed code. You can either assume you don't need the unused code or adjust your gulp file as such:

    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'));
    });