javascriptgulpecmascript-6gulp-uglify

Gulp uglify unable to handle arrow functions


I'm trying to compress my project using gulp-uglify, however gulp seems to throw the error Unexpected token: punc () whenever it encounters an arrow function in the code. Is there anything I can do to fix this? Thank you.

gulp-crash-test.js

// Function with callback to simulate the real code
function test(callback) {
    if (typeof callback === "function") callback();
}

// Causes a crash
test(() => {
    console.log("Test ran successfully!");
});

// Doesn't cause a crash
test(function () {
    console.log("Test ran successfully!");
});

gulpfile.js

var gulp = require("gulp");
var concat = require("gulp-concat");
var uglify = require("gulp-uglify");

gulp.task("scripts", function() {
    gulp.src([
        "./gulp-crash-test.js"
    ]).pipe(
        concat("gulp-crash-test.min.js")
    ).pipe(
        uglify().on('error', function(e){
            console.log(e);
        })
    ).pipe(
        gulp.dest("./")
    );
});

gulp.task("watch", function() {
    gulp.watch("./gulp-crash-test.js", ["scripts"]);
});

gulp.task("default", ["watch", "scripts"]);

Solution

  • Arrow functions are an ES6 feature. Babel (and others) are designed to translate ES6 to ES5 or earlier as part of your build process. Luckily there are Babel plug-ins for Gulp and Grunt. Run Babel before uglify.

    https://www.npmjs.com/package/gulp-babel

    I hope this steers you in the right direction/somebody can demonstrate some code.