Good Practice Gulpfile.js

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 it works.

but the tutorial that I follow has a little 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 .on ('change', browserSync.reload)? it works; I'm just curious that what I'm doing is not a good practice. Thanks!

+7
javascript gulp gulp-sass gulp-watch
source share
2 answers

No, you do not need to add custom on('change') . You must pass an event handler when initializing the observer, like a tutorial. Otherwise, as if saying gulp did nothing when changing by default, then add your listener.

Another advantage is that you can pass multiple event handlers at a time as an array if your handlers are gulp tasks themselves gulp.watch(..., ['task1', 'task2']) instead of the on('change', task1Function).on('change', task2Function)

+1
source share

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

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

watch you can call a function with the following parameters: gulp.watch(glob [, opts], tasks) or gulp.watch(glob [, opts, cb]) .

Thus, you can use both options, but it is preferable to use a shorter method.

+1
source share

All Articles