Search code examples
gulpgulp-watch

Gulp Fix "gulp.run() has been deprecated" for Server Livereload


I'm new to Gulp and I found a Gulpfile.js example I wanted to use to livereload my express app's server whenever a change takes place in either my app.js file or ./public directory. Here is the Gulpfile.js code:

var gulp = require('gulp'),
    spawn = require('child_process').spawn,
    node;

/**
 * $ gulp server
 * description: Launch the server. If there's a server already running, kill it.
 */
gulp.task('server', function() {
  if (node) node.kill()

  node = spawn('node', ['app.js'], {stdio: 'inherit'})

  node.on('close', function (code) {
    if (code === 8) {
      gulp.log('Error detected, waiting for changes...');
    }
  });
})

/**
 * $ gulp default
 * description: Start the development environment
 */
gulp.task('default', function() {
  gulp.run('server')

  gulp.watch(['./app.js', './public/'], function() {
    gulp.run('server')
  })
})

// clean up if an error goes unhandled.
process.on('exit', function() {
    if (node) node.kill()
})

In my terminal window I keep getting the following warning:

gulp.run() has been deprecated. Use task dependencies or gulp.watch task triggering instead.

Gulp is working and it is livereloading the web application like I want it to but I'd like to fix this issue to future proof my development process, as well as get rid of this annoying warning message.

Thanks for the help!


Solution

  • One option would be to simply replace all occurrences of gulp.run() with gulp.start():

    gulp.task('default', function() {
      gulp.start('server');
    
      gulp.watch(['./app.js', './public/'], function() {
        gulp.start('server');
      });
    });
    

    However calling a task explicitly using gulp.start() is not the idiomatic way of doing things in gulp (although sometimes it's necessary).

    The warning message you receive already hints at the idiomatic way of solving this:

    Use task dependencies or gulp.watch task triggering

    • Task dependencies allow you to run a task before another task. That means you can get rid of the first gulp.run().
    • Task triggering in gulp.watch() allows you to run a task when a file changes. That means you can get rid of the second gulp.run().

    Therefore your default task ends up looking like this:

    gulp.task('default', ['server'], function() {
      gulp.watch(['./app.js', './public/'], ['server']);
    });