Introduction to Gulp.js 8: Watch for Changes

This is the 8th part of my series, Introduction to Gulp.js. Today, I will set up watch tasks for many files with Gulp.js.

Do you remember the watch task from the beginning? It started BrowserSync and the development server until now, but didn’t watch for anything. I will write these watch tasks now.

Watch is part of the API of gulp. It will watch files for changes, addition or deletion, and trigger tasks.


watch: {
jekyll: [
src + '/_data/**/*.{json,yml,csv}',
src + '/_includes/**/*.{html,xml}',
src + '/_layouts/*.html',
src + '/_plugins/*.rb',
src + '/_posts/*.{markdown,md}',
src + '/**/*.{html,markdown,md,yml,json,txt,xml}',
src + '/*'
sass: srcAssets + '/scss/**/*.{sass,scss}',
scripts: srcAssets + '/javascripts/**/*.js',
images: srcAssets + '/images/**/*',
sprites: srcAssets + '/images/**/*.png',
svg: 'vectors/*.svg'

I watch countless different file types for Jekyll. Changes in configuration files, data files, layouts, including plugins, and posts.

The Sass task will watch for changes in files with the suffix sass or scss. JavaScript gets triggered if I change JavaScript files. You get the point.


var gulp = require("gulp");
var config = require("../../config").watch;

* Start browsersync task and then watch files for changes

gulp.task("watch", ["browsersync"], function () {, ["jekyll-rebuild"]);, ["sass", "scsslint"]);, ["scripts", "jshint"]);, ["images"]);, ["copy:fonts"]);, ["sprites"]);

I set up six watch tasks. When a file of the Jekyll watch gets changed, deleted, or added, the jekyll-rebuild task gets executed. This task will run the Jekyll build, and after it’s finished reload the page.

For SCSS files, I run the sass tasks, and additionally, I run a scsslint task, which will check my files for syntax errors.

Changes in JavaScript files trigger the scripts tasks and a jshint task, which will check my files for syntax errors.

If I add, modify or delete an SVG file, my vector fonts get recreated. And as a fallback for browsers without vector font support, I create a PNG sprite map when I change an image of the sprite. It would be possible to auto-create the PNG files of the SVG files with gulp-svg2png, but I have an additional design on the sprite images, that’s why I don’t use it.

I miss now three tasks: scsslint, jshint, and sprites.


This concludes the 8th part of my series, Introduction to Gulp.js. We learned how to use Gulp.js to watch for changes, deletion, or creation of files and how to trigger tasks. And the best part is: This is part of the Gulp.js API. We don’t need any plugins.

View Source on GitHub