Why doesn't live reload work with gulp-connect?

Misha Moroshko picture Misha Moroshko · Apr 10, 2014 · Viewed 14.2k times · Source

I use gulp-connect like this:

gulp.task('watch', function() {
  gulp.watch(paths.scss, ['scss']);

  gulp.watch(distPaths, function() {
    return gulp.src(distPaths)
               .pipe(connect.reload());
  });
});

The live reload bit works fine.

My question is, why the following doesn't work:

gulp.task('watch', function() {
  gulp.watch(paths.scss, ['scss']);
  gulp.watch(distPaths, connect.reload);
});

What the gulp.src(distPaths) bit is for?

Also, what's the importance of return?

Answer

OverZealous picture OverZealous · Apr 10, 2014
  1. connect.reload() needs to be used in a stream. In your example, you're trying to call it as a standalone function, which does nothing. Calling connect.reload() returns a stream handler that takes input and does something with it. It's effectively a no-op in the second example.

  2. You need return or tasks are run synchronously. (You can also return a promise or use the callback function.)

    Basically, if you don't provide some way for gulp to track the progress of your asynchronous tasks, it has to assume they are complete when you return from the function. If you return the pipe, it can listen to for it to reach the end.

Also, it might work better to use gulp-watch for your watch, because it only passes through the changed files, which is what you want for live reload:

var watch = require('gulp-watch');

gulp.task('watch', function() {
    gulp.watch(paths.scss, ['scss']);
    watch(distPath).pipe(connect.reload());
});