Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Gulp-Watch Multiple files?

I have something like this:

gulp.task('default', ['css', 'browser-sync'] , function() {

    gulp.watch(['sass/**/*.scss', 'layouts/*.css'], function() {
        gulp.run('css');
    });

});

but it does not work, because it watches two directories, the sass and the layouts directory for changes.

How do I make it work, so that gulp watches anything that happens inside those directories?

like image 699
LoveAndHappiness Avatar asked Dec 25 '14 07:12

LoveAndHappiness


3 Answers

gulp.task('default', ['css', 'browser-sync'] , function() {

    gulp.watch(['sass/**/*.scss', 'layouts/**/*.css'], ['css']);

});

sass/**/*.scss and layouts/**/*.css will watch every directory and subdirectory for any changes to .scssand .css files that change. If you want to change that to any file make the last bit *.*

like image 156
Kelly J Andrews Avatar answered Nov 14 '22 22:11

Kelly J Andrews


You can write a watch like this.

gulp.task('watch', function() {
    gulp.watch('path/to/file', ['gulp task name for css/scss']);
    gulp.watch('path/to/file', ['gulp task name for js']);
});

This way you can set up as many tasks as you want via the file path of what you want to watch followed by the name of the task you created. Then you can write your default like this:

gulp.task('default', ['gulp task name for css/scss', 'gulp task name for js']);

If you want to simply watch for various file changes, then just watch files using glob like *.css in your task.

like image 36
P. Alger Avatar answered Nov 14 '22 22:11

P. Alger


One problem that has arisen for multiple people (including me) is that adding a gulp.filter outside of the task causes gulp.watch to fail after the first pass. So if you have something like this:

var filter = gulpFilter(['fileToExclude.js'])
gulp.task('newTask', function(){ ...

Then you need to change it to:

gulp.task('newTask', function(){
  var filter = gulpFilter(['fileToExclude.js'])

The filter has to be included in the task function. Hope that helps someone.

like image 10
Lyra Avatar answered Nov 15 '22 00:11

Lyra