7

here is my current watchlist for my gulpfile.js

// Gulp watchlist
gulp.task('watch', ['browserSync', 'sass'], function(){
    gulp.watch('app/scss/**/*.scss', ['sass']);
    gulp.watch('app/*.html').on('change', browserSync.reload);
    gulp.watch('app/js/**/*.js').on('change', browserSync.reload);
    //add more watchers here
});

and this works.

but a tutorial i am following has something slightly different:

gulp.task('watch', ['browserSync', 'sass'], function (){
  gulp.watch('app/scss/**/*.scss', ['sass']); 
  // Reloads the browser whenever HTML or JS files change
  gulp.watch('app/*.html', browserSync.reload); 
  gulp.watch('app/js/**/*.js', browserSync.reload); 
});

do I need the .on('change', browserSync.reload)? it works; I'm just curious if what i'm doing isn't good practice. Thanks!

Sven Schoenung
  • 30,224
  • 8
  • 65
  • 70
Brock Vond
  • 216
  • 2
  • 7

2 Answers2

1

Gulp watch always returns an EventEmitter that emits change events, so the call gulp.watch('app/*.html').on('change', browserSync.reload) can be written as:

var watcher = gulp.watch('app/*.html');
watcher.on('change', browserSync.reload);

watch function can be called with the following params: gulp.watch(glob [, opts], tasks) or gulp.watch(glob [, opts, cb]).

So you can use both variants, but the shorter method is preferable.

Chirag Bhatia - chirag64
  • 4,430
  • 3
  • 26
  • 35
alexmac
  • 19,087
  • 7
  • 58
  • 69
1

No, you don't need to add custom on('change'). You should pass the event handler when initializing the watcher like the tutorial. Otherwise, it's sort of like telling gulp to do nothing on change by default then add your listener afterwards.

Another advantage is you can pass in multiple event handlers in one go as an array if your handlers are gulp tasks themselves gulp.watch(..., ['task1', 'task2']) instead of chaining on('change', task1Function).on('change', task2Function)

Lim H.
  • 9,870
  • 9
  • 48
  • 74
  • I see, thank you ... i have follow up question then I guess... the order of the array matters, right? So if I want to minify everything before the broswersync reload i should prob just have browsersync at the end of the array yeah? or... no? lol – Brock Vond Apr 08 '16 at 12:55
  • Yes that is correct :) but then you need to realize that gulp tasks are async in nature so I would make a function instead and call your handlers synchronously! – Lim H. Apr 08 '16 at 13:03