Search code examples
gulpjshintgulp-jshint

gulp stops server on error even with jshint included in gulpfile.js


I don't know why the server still stops whenever there's an error in my js files even though I have jshint in my gulpfile. I installed jshint and included it in my project because it reports errors in js files, but it's still failing. How can I fix this?

gulp.task('scripts', () => {
    return gulp.src('assets/js/src/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish', {beep: true}))
        .pipe(concat('main.js'))
        .pipe(gulp.dest('assets/js/build/'))
        .pipe(uglify())
        .pipe(gulp.dest('assets/js/'))
        .pipe(browserSync.stream({stream: true}));
});

Solution

  • gulp-jshint does what you says it does: it reports errors in JavaScript files. Nothing more, nothing less. It doesn't prevent defective JavaScript files from reaching later pipe stages like uglify() (which throws up and thus stops your server if there's any error in a JavaScript file).

    If you want to prevent defective JavaScript files from wrecking your server, you need to put all the jshint stuff into it's own task and make sure that task fails when any JavaScript file has an error:

    gulp.task('jshint', () => {
        return gulp.src('assets/js/src/*.js')
            .pipe(jshint())
            .pipe(jshint.reporter('jshint-stylish', {beep: true}))
            .pipe(jshint.reporter('fail'))
    });
    

    Then you need to make your scripts task depend on that jshint task:

    gulp.task('scripts', ['jshint'], () => {
        return gulp.src('assets/js/src/*.js')
            .pipe(concat('main.js'))
            .pipe(gulp.dest('assets/js/build/'))
            .pipe(uglify())
            .pipe(gulp.dest('assets/js/'))
            .pipe(browserSync.stream({stream: true}));
    });
    

    Now your scripts task will only run when the jshint task was successful. If any JavaScript file was defective jshint will output the error to the console while your server continues to run using the last good version of your JavaScript.