Gulp – Watch

Gulp, Gulp – Watch

Now for something super amazing. Instead of running the gulp task explicitly, lets have gulp run our tasks when the files change.

First reorganize some of our tasks:
- Rename default task to css.
- Create a new default task to run css, ‘javascript’, and ‘homepage’ tasks.

gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
...
gulp.task('css', ['clean'], function() {
  console.log("Concat, move, and minify all the css files in styles folder");
  return gulp.src("contents/styles/**.css")
    .pipe(concat('main.min.css'))
    .pipe(cssmin())
    .pipe(gulp.dest('build/styles'));
});
...
gulp.task('default', ['css', 'homepage', 'javascript']);
...

Next create our file watching task. Could you guess what?… there isn’t a plugin for this. It is just part of gulp.

We will create a gulp watch task to watch our contents folder and run our default task on file change.

gulpfile.js
1
2
3
4
5
...
gulp.task('watch', [], function() {
  return gulp.watch(['contents/**'], ['default']);
});
...

In the terminal type:

1
2
3
4
5
$ gulp watch

Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'watch'...
Finished 'watch' after 11 ms

If you update any of the css files in the styles folder, you should see gulp run the default task.

1
2
3
4
5
6
7
8
9
10
11
12
13
Starting 'clean'...
Clean all files in build folder
Finished 'clean' after 21 ms
Starting 'css'...
Concat, move, and minify all the css files in styles folder
Starting 'homepage'...
Starting 'javascript'...
Validate, Concat, Uglify, and Move all the javascript files
Finished 'homepage' after 77 ms
Finished 'javascript' after 75 ms
Finished 'css' after 84 ms
Starting 'default'...
Finished 'default' after 14 μs