Search code examples
node.jsgulp-watchgulp-connect

How to setup gulp-watch with gulp-connect livereload?


Most questions and answers on this site do not contain an easy-to follow general approach to using these two libraries together.

So, being that we use the gulp-connect npm package, and we want to make use of the gulp-watch npm package, how do we set it up so that we can:

  • watch changes in some files
  • perform some operation, like building / compiling those files
  • live-reload the server once the building is done

Solution

  • First, you will define your build task. This can have pre-required tasks, can be a task of some sort, it doesn't matter.

    gulp.task('build', ['your', 'tasks', 'here']);
    

    Then, you will need to activate the connect server. It is important that you are serving the result of the compilation (in this example, the dist directory) and you're enabling livereload with the livereload: true parameter.

    const connect = require('gulp-connect');
    
    gulp.task('server', function() {
      return connect.server({
        root: 'dist',
        livereload: true
      });
    });
    

    Finally, you will setup your watch logic. Note that we're using watch and not gulp.watch. If you decide to change it, notice that their APIs are different and they have different capabilities. This example uses gulp-watch.

    const watch = require('gulp-watch');
    
    gulp.task('watch-and-reload', ['build'], function() {
      watch(['src/**'], function() {
        gulp.start('build');
      }).pipe(connect.reload());
    });
    
    gulp.task('watch', ['build', 'watch-and-reload', 'server']);
    

    The watch-and-reload task will depend on the build task, so that it ensures to run at least one build.

    Then, it will watch for your source files, and in the callback, it will start the build task. This callback gets executed every time that a file is changed in the directory. You could pass an options object to the watch method to be more specific. Check the usage API in their repository.

    Also, you will need to start the build action, for which we're using gulp.start. This is not the recommended approach, and will be deprecated eventually, but so far it works. Most questions with these issues in StackOverflow will look for an alternative workaround that changes the approach. (See related questions.)

    Notice that gulp.start is called synchronously. This is what you want, since you want to allow the build task to finish before you proceed with the event stream.

    And finally, you can use the event stream to reload the page. The event stream will correctly capture what files changed and will reload those.