Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"]);
like image 635
Paradoxis Avatar asked Mar 23 '16 13:03

Paradoxis


3 Answers

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.

like image 73
Jxx Avatar answered Oct 19 '22 15:10

Jxx


There is no supporting ugilify(minify) tools for ES6 Syntax. you should be build gulp task after babel compile (es6 -> es5)

1.Install packages

npm install gulp-babel babel-preset-es2015

2.change your code as below.

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

    gulp.task("scripts", function() {
        return gulp.src(["./gulp-crash-test.js"])
    .pipe(babel({presets: ['es2015']}))
    .pipe(concat("gulp-crash-test.minjs"))
    .pipe(uglify().on('error', function(e){
         console.log(e);
    }))
    .pipe(gulp.dest("./"))
    });
like image 24
superui Avatar answered Oct 19 '22 15:10

superui


You can use babel minify (previously Babili) a library based on babel to minify ES6 code without transpiling:

First install via npm:

npm install --save-dev babel-preset-minify

Then in your gulp file:

var gulp = require('gulp')
var babel = require('gulp-babel')
gulp.task('default', () => {
  return gulp.src('src/app.js')
  .pipe(babel({presets: ['minify']}))
  .pipe(gulp.dest('dist'))
})

It uses babel as a parser, but there is no transpilation.

like image 11
Gabriel Furstenheim Avatar answered Oct 19 '22 15:10

Gabriel Furstenheim