Gulp 4 - watch not watching changes

Martin Hetfield Mali picture Martin Hetfield Mali · Jan 7, 2018 · Viewed 7.4k times · Source

Today I migrated to Gulp 4, but I'm not able to get my watch function to work.

// Watch
gulp.task('watch', gulp.series('typescript', 'sass', 'browserSync', function(){
  gulp.watch('./app/styles/**/*.scss', gulp.series('sass'));
  gulp.watch('app/scripts/**/*.ts', gulp.series('typescript'));
  gulp.watch('./app/*.html', browserSync.reload);
}));

typescript, sass, browserSync will run but watch does not react to file changes.

Answer

Neil VanLandingham picture Neil VanLandingham · Dec 17, 2018

I just had the same problem. You don't actually have a reference to the initialized browserSync inside your watch gulp task. Instead of having your browserSync.init function in a separate browserSync gulp task, move it to inside your watch task, and it should work. Hope this helps!

Example:

gulp.task('watch', gulp.series(function (){
  browserSync.init({
    proxy:"http://localhost:8888",
    injectChanges: true,
    plugins: ["bs-html-injector?files[]=*.html"]
  });
  var html = gulp.watch('development/index.html');
  html.on('change', function(path, stats) {
    console.log('you changed the html');
    browserSync.notify("Compiling, please wait!");
    browserSync.reload("index.html");
  })
  var js = gulp.watch('development/**/*.js');
  js.on('change', function(path, stats) {
    console.log('you changed the js');
    browserSync.notify("Compiling, please wait!");
    browserSync.reload();
  })
  var css = gulp.watch('development/**/*.css');
  css.on('change', function(path, stats) {
    console.log('you changed the css');
    browserSync.notify("Injecting CSS!");
    browserSync.reload("*.css");
  })
}));