Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching and handling Uglify errors when using Gulp

My Gulp setup is otherwise working fantastically, but it stops if there's an error with my JS files. Until Gulp 4 is finally released, we're all stuck using the less than perfect error system in Gulp... So how can I catch Uglify's errors?

gulp.task('js', function() {
    return gulp
        .src(inputJS)
        .pipe(sourcemaps.init())
        .pipe(concat('main.js'))
        .pipe(uglify(uglifyOptions))
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest(outputJS))
});

According to the Uglify documentation, gulp-uglify emits an 'error' event if it is unable to minify a specific file. Wherever possible, the PluginError object will contain the following properties: fileName, lineNumber, message.

The closest I've gotten it to working is: .on('error', function(uglify) { console.error(uglify.message) })), but it ends up with the above Gulp task ceasing to do any more.

Edit: I realise that there's a number of Gulp extensions that help when dealing with error handling (eg. Gulp-Util, Stream-Combiner2, Gulp-Plumber, etc.) but I don't wish to install a whole new extension just for Uglify (I'm handling my Sass errors just fine without one).

like image 728
Chuck Le Butt Avatar asked Mar 23 '26 00:03

Chuck Le Butt


1 Answers

It seems the solution was very simple:

    .pipe(uglify(uglifyOptions).on('error', function(uglify) {
        console.error(uglify.message);
        this.emit('end');
    }))

Almost exactly what Jeffwa suggested, but no need for gulp-plumber. The reason my attempt was stopping is because Gulp watch tasks wait until they receive end (see: https://github.com/gulpjs/gulp/issues/259).

like image 180
Chuck Le Butt Avatar answered Mar 24 '26 21:03

Chuck Le Butt