How can Gulp be restarted upon each Gulpfile change?

Solution 1:

You can create a task that will gulp.watch for gulpfile.js and simply spawn another gulp child_process.

var gulp = require('gulp'),
    argv = require('yargs').argv, // for args parsing
    spawn = require('child_process').spawn;

gulp.task('log', function() {
  console.log('CSSs has been changed');
});

gulp.task('watching-task', function() {
  gulp.watch('*.css', ['log']);
});

gulp.task('auto-reload', function() {
  var p;

  gulp.watch('gulpfile.js', spawnChildren);
  spawnChildren();

  function spawnChildren(e) {
    // kill previous spawned process
    if(p) { p.kill(); }

    // `spawn` a child `gulp` process linked to the parent `stdio`
    p = spawn('gulp', [argv.task], {stdio: 'inherit'});
  }
});

I used yargs in order to accept the 'main task' to run once we need to restart. So in order to run this, you would call:

gulp auto-reload --task watching-task

And to test, call either touch gulpfile.js or touch a.css to see the logs.

Solution 2:

I created gulper that is gulp.js cli wrapper to restart gulp on gulpfile change.

You can simply replace gulp with gulper.

$ gulper <task-name>

Solution 3:

I use a small shell script for this purpose. This works on Windows as well.

Press Ctrl+C to stop the script.

// gulpfile.js
gulp.task('watch', function() {
    gulp.watch('gulpfile.js', process.exit);
});

Bash shell script:

# watch.sh
while true; do
    gulp watch;
done;

Windows version: watch.bat

@echo off
:label
cmd /c gulp watch
goto label