Gulp - Watch


Advertisements

The Watch method is used to monitor your source files. When any changes to the source file is made, the watch will run an appropriate task. You can use the ‘default’ task to watch for changes to HTML, CSS, and JavaScript files.

Update Default Task

In the previous chapter you have learnt how to gulp combining tasks using 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.watch('src/styles/*.css', function() {
      // run styles upon changes
      gulp.run('styles');
   });
});

All the CSS files under work/src/styles/ folder will be watched and upon changes made to these files, the styles task will be executed.

Run Default Task

Run the ‘default’ task using the following command.

gulp

After executing the above command, you will receive the following output.

C:\work>gulp
[17:11:28] Using gulpfile C:\work\gulpfile.js
[17:11:28] Starting 'styles'...
[17:11:28] Finished 'styles' after 22 ms
[17:11:28] Starting 'default'...
[17:11:28] Finished 'default' after 21 ms

Whenever any changes are made to CSS files, you will receive the following output.

C:\work>gulp
[17:11:28] Using gulpfile C:\work\gulpfile.js
[17:11:28] Starting 'styles'...
[17:11:28] Finished 'styles' after 22 ms
[17:11:28] Starting 'default'...
[17:11:28] Finished 'default' after 21 ms
gulp.run() has been deprecated. Use task dependencies or gulp.watch task 
   triggering instead.
[17:18:46] Starting 'styles'...
[17:18:46] Finished 'styles' after 5.1 ms

The Watch process will remain active and respond to your changes. You can press Ctrl+Cto terminate the monitoring process and return to the command line.

Advertisements