2

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).

1
  • 1
    Why do you have an avatar from one of the worst Star Trek episodes?! Commented Nov 16, 2015 at 17:00

2 Answers 2

11

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).

Sign up to request clarification or add additional context in comments.

1 Comment

@Chunck It works but the reference for the error is filename: 'script.js' in the /dist folder. How do I find out which js file before concat'ing is the reason for the error? Thanks in advance.
1

Maybe gulp-plumber will help.

var plumber = require('gulp-plumber');

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

That should catch any errors emitted and write them to the console.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.