Prevent errors from breaking / crashing gulp watch

后端 未结 8 841
我在风中等你
我在风中等你 2020-12-12 09:17

I\'m running gulp 3.6.2 and have the following task that was set up from a sample online

gulp.task(\'watch\', [\'default\'], function () {
  gulp.watch([
            


        
8条回答
  •  时光说笑
    2020-12-12 09:42

    Your swallowError function should look like this:

    function swallowError (error) {
    
      // If you want details of the error in the console
      console.log(error.toString())
    
      this.emit('end')
    }
    

    I think you have to bind this function on the error event of the task that was falling, not the watch task, because that's not where comes the problem, you should set this error callback on each task that may fail, like plugins that breaks when you have missed a ; or something else, to prevent watch task to stop.

    Examples :

    gulp.task('all', function () {
      gulp.src('./app/script/*.coffee')
        .pipe(coffee({ bare: true }))
        .on('error', swallowError)
        .pipe(gulp.dest('./public/js'))
    
      gulp.src('css/*.scss')
        .pipe(sass({ compass: true }))
        .on('error', swallowError)
        .pipe(cssmin())
        .pipe(gulp.dest('dist'))
    })
    

    Alternately, if you don't mind to include another module, you can use the log function of gulp-util to keep you from declare an extra function in your gulpfile:

    .on('error', gutil.log)
    

    But I may recommend having a look at the awesome gulp-plumber plugin, which is used to remove the onerror handler of the error event, causing the break of the streams. It's very simple to use and it stops you from catch all the tasks that may fail.

    gulp.src('./app/script/*.coffee')
      .pipe(plumber())
      .pipe(coffee({ bare: true }))
      .pipe(gulp.dest('./public/js'))
    

    More info about this on this article by the creator of the concerned plugin.

提交回复
热议问题