How to solve this minification error on Gulp?
Asked Answered
T

2

31

I'm getting below error running this command

gulp.task('minify', function () {
    return gulp
      .src('public/app/js/myapp.bundle.js')
      .pipe(uglify())
      .pipe(gulp.dest('public/app/js/myapp.bundle.min.js'));
});

GulpUglifyError: unable to minify JavaScript Caused by: SyntaxError: Unexpected token: name (MenuItem) (line: 1628, col: 18, pos: 53569)

Code on that location is this

 setters: [],
 execute: function () {
     class MenuItem {  // <-- line 1628

What's wrong?

Tarantella answered 11/8, 2016 at 3:35 Comment(2)
Possible duplicate of how to uglify javascript classes?Fredelia
TL;DR - class keyword is the problemNatheless
G
69

UglifyJS does not currently support EcmaScript 6 structures like classes.

You'll probably need to run your JavaScript through a transpiler step first, or find a minifier that knows what to do with ES6 code.

Update 2017-06-17

The branch of UglifyJS that is designed to work with ES6 is now published as uglify-es on npm.

Update 2018-09-10

terser is the new uglify-es, uglify-es is no longer maintained.

If using gulp both npmjs gulp-uglify-es and npmjs gulp-terser packages support terser.

npm install gulp-terser --save-dev
const gulp = require('gulp');
const terser = require('gulp-terser');
 
function es(){
  return gulp.src('./src/index.js')
    .pipe(terser())
    .pipe(gulp.dest('./build'))
}

gulp.task('default', es);
Gristede answered 11/8, 2016 at 3:50 Comment(3)
UglifyJS should get updated then. It seems like a fair amount of people use this and would use this especially if there were one less step.Marras
@SMT: Agreed. And I get the impression they've been working on it. They've got a "harmony" version published as uglify-es now, which ditches some backwards API compatibility in favor of supporting ES6.Gristede
yeah i subscribed to one github issue in particular in that repo which is about this. still an ongoing discussion and not resolved yet @StriplingWarrior. Part of me just wants to be snarky and point out Sputnik 1 took 3 years to design and create and launch, yet 3 years isnt enough time to add in ES6 support for minification. :/Marras
S
6

If you run into this problem and you have in fact a transpiler step like Babel, make sure that you include the proper Babel preset in you .babelrc file. Otherwise Babel will simply leave your code as is.

E.g.

{
  "presets": ["es2015"]
}
Sourdough answered 14/1, 2017 at 20:4 Comment(2)
Can you please elaborate on this? What exactly should be included in the .babelrc file?Manhour
I've added an exampleSourdough

© 2022 - 2024 — McMap. All rights reserved.