How to minify ES6 functions with gulp-uglify?

2019-01-17 10:40发布

问题:

When I run gulp I get the following error:

[12:54:14] { [GulpUglifyError: unable to minify JavaScript]
cause:
{ [SyntaxError: Unexpected token: operator (>)]
 message: 'Unexpected token: operator (>)',
 filename: 'bundle.js',
 line: 3284,
 col: 46,
 pos: 126739 },
plugin: 'gulp-uglify',
fileName: 'C:\\servers\\vagrant\\workspace\\awesome\\web\\tool\\bundle.js',
showStack: false }

The offending line contains an arrow function:

var zeroCount = numberArray.filter(v => v === 0).length

I know I can replace it with the following to remedy the minification error:

var zeroCount = numberArray.filter(function(v) {return v === 0;}).length

How can I run gulp on code containing ES6 features without causing minification to fail?

回答1:

You can leverage gulp-babel as such...

let gulp = require('gulp');
let babel = require('gulp-babel');
let uglify = require('gulp-uglify');

gulp.task('minify', () => {
  return gulp.src('src/**/*.js')
    .pipe(babel({
      presets: ['es2015']
    }))
    .pipe(uglify())
    // [...]
});

This will transpile your es6 early in the pipeline and churn out as widely supported "plain" javascript by the time you minify.


May be important to note - as pointed out in comments - the core babel compiler ships as a peer dependency in this plugin. In case the core lib is not being pulled down via another dep in your repo, ensure this is installed on your end.

Looking at the peer dependency in gulp-babel the author is specifying @babel/core (7.x). Though, the slightly older babel-core (6.x) will work as well. My guess is the author (who is the same for both projects) is in the midsts of reorganizing their module naming. Either way, both npm installation endpoints point to https://github.com/babel/babel/tree/master/packages/babel-core, so you'll be fine with either of the following...

npm install babel-core --save-dev

or

npm install @babel/core --save-dev


回答2:

The accepted answer doesn't really answer how to minify straight es6. If you want to minify es6 without transpiling, gulp-uglify v3.0.0 makes that possible:

1.) First, upgrade your gulp-uglify package to > 3.0.0 If you're using yarn and want to update to the latest version:

yarn upgrade gulp-uglify --latest

2.) Now you can use uglify-es, the "es6 version" of uglify, as so:

const uglifyes = require('uglify-es');
const composer = require('gulp-uglify/composer');
const uglify = composer(uglifyes, console);

gulp.task('compress', function () {
    return gulp.src('src/*.js')
    .pipe(uglify())
    .pipe(gulp.dest('dist'))
});

For more info: https://www.npmjs.com/package/gulp-uglify



回答3:

You actually can uglify ES6 code without transpilation. Instead of gulp-uglify plugin, use gulp-uglifyes plugin.

var gulp = require('gulp');
var rename = require('gulp-rename'); 
var uglify = require('gulp-uglifyes');
var plumber = require('gulp-plumber');
var plumberNotifier = require('gulp-plumber-notifier');
var sourcemaps = require('gulp-sourcemaps');
var runSequence = require('run-sequence').use(gulp);

gulp.task('minjs', function () {
  return gulp.src(['/dist/**/*.js', '!/dist/**/*.min.js'])
    .pipe(plumberNotifier())
    .pipe(sourcemaps.init())
    .pipe(uglify({ 
       mangle: false, 
       ecma: 6 
    }))
    .pipe(rename(function (path) {
      path.extname = '.min.js';
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('/dist'));
});


回答4:

unfortunately, as per now, you can't use uglify with es-next code, you can:

  1. Transpile to ES5using Babel
  2. Use Babili instead of Uglify.


回答5:

gulp-uglify:

For ES6 and newer.

  1. install: npm install --save-dev gulp-uglify
  2. install: npm install --save-dev gulp-babel @babel/core @babel/preset-env

Usage:

const gulp = require('gulp'); 
const uglify = require('gulp-uglify');
const babel = require('gulp-babel');

gulp.task('script', () => {
    return gulp.src('src/**/*.js')
        .pipe(babel({
            presets: ['@babel/env']
        }))
        .pipe(uglify())
        .pipe(gulp.dest('src/dist'))
});