Gulp Watch

Learning Gulp : part 14 of 22 published on Aug 10, 2015

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

First lets reorganize some of our tasks.

  • Rename default task to css
  • Create a new default task to run css, ‘javascript’, and ‘homepage’ tasks
// /gulpFile.js
...
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 lets create our file watching task. 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
...
gulp.task('watch', [], function() {
  return gulp.watch(['contents/**'], ['default']);
});
...

At the terminal type:

$ 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.

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
Next: Web server