Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gulpfile.js watch best practice

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!

like image 640
Brock Vond Avatar asked Apr 08 '16 10:04

Brock Vond


People also ask

What is gulp watch command?

The watch() API connects globs to tasks using a file system watcher. It watches for changes to files that match the globs and executes the task when a change occurs. If the task doesn't signal Async Completion, it will never be run a second time.

How do I minify JavaScript using gulp?

js, first declare the dependencies as shown in the following code. var gulp = require('gulp'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var minify = require('gulp-minify-css'); Next, you need to create tasks for optimizing CSS and JavaScript as shown in the following code. gulp.

How do I watch gulp?

Update Default Task We used gulp-minify-css, gulp-autoprefixer and gulp-concatplugins, and created styles task to minify CSS files. To watch CSS file, we need to update the 'default' task as shown in the following code: gulp. task('default', ['styles'], function() { // watch for CSS changes gulp.


2 Answers

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)

like image 188
Lim H. Avatar answered Oct 11 '22 02:10

Lim H.


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.

like image 42
alexmac Avatar answered Oct 11 '22 03:10

alexmac