Search code examples
javascriptgulpnode-streams

Gulp watch with browserSync


I'm trying to write a gulp file that do the following:

  1. Runs watch task that rebuilds Handlebars templates on any template change.
  2. If build fails it notifies BrowserSync via notify() method so I can see popup in browser if something goes wrong. Watch should't be stopped.
  3. If build is ok it calls browserSync.reload().

So I came up with following pice of code:

function SomeTask() {
  return gulp.src('*.hbs')
         .pipe(plumber())
         .pipe(somePlugin1())
         .pipe(somePlugin2())
         .pipe(gulp.dest('dest'));
}

gulp.watch(['*.hbs'], function(event) {
  SomeTask()
  .on('error', function(error) {
    browserSync.notify('ERROR!');
  })
  .on('end', browserSync.reload)
})

The problem is that if I use gulp-plumber 'end' event is emmits and browserSync.reload() is called. So I didn't see any error notification in browser. On the other hand without "plumber" any build error breaks watch task.

Any ideas?


Solution

  • gulp-plumber let's you provide a custom errorHandler function. You can put your browserSync.notify() call in there:

    function SomeTask(handler) {
      return gulp.src('*.hbs')
        .pipe(plumber({errorHandler: handler}))
        .pipe(somePlugin1())
        .pipe(somePlugin2())
        .pipe(gulp.dest('dest'));
    }
    
    gulp.watch(['*.hbs'], function(event) {
      var failed = false;
      SomeTask(function(error) {
        browserSync.notify('ERROR: ' + error.message);
        console.log(error.toString());
        failed = true;
      })
      .on('end', function() {
        if (!failed) {
          browserSync.reload();
        }
      });
    });