javascriptgulpgulp-uglify

Unexpected Token when trying to minimize code using Uglify


I am running the following gulp task:

   var gulp = require('gulp');
   var uglify = require('gulp-uglify');
   var rename = require('gulp-rename');

    gulp.task('uglify', function(){
         gulp.src('htdocs/js/*.js')
             .pipe(uglify())
             .pipe(rename({suffix: '.min'}))
             .pipe(gulp.dest('dist'));
    });

When I do so I get the following error:

GulpUglifyError: unable to minify JavaScript
Caused by: SyntaxError: Unexpected token: punc «{», expected: punc «;»

It is failing on the first line of the first JavaScript file. The line it objects to is:

import {removeScoreButtons} from './display.js';

Solution

  • If you have code in ES6 you have to transpile it to ES5 with gulp-babel before uglify. Something like this:

    var gulp = require('gulp');
    var uglify = require('gulp-uglify');
    var rename = require('gulp-rename');
    var babel = require('gulp-babel');
    
    gulp.task('uglify', function(){
         gulp.src('htdocs/js/*.js')
             .pipe(babel({
                presets: ['@babel/env']
             }))
             .pipe(uglify())
             .pipe(rename({suffix: '.min'}))
             .pipe(gulp.dest('dist'));
    });
    

    Here you have more information: https://www.npmjs.com/package/gulp-babel