Search code examples
gulp

gulp.watch - To return or not return


The official documentation for gulpjs/gulp has a sample gulpfile.js which provides a watch task that has no return statement:

gulp.task('watch', function() { gulp.watch(paths.scripts, ['scripts']); gulp.watch(paths.images, ['images']); });

That approach fits my needs, because I want to watch over multiple sets of files with different tasks associated to each of them.

But I've found in the community a few bold statements saying that gulp.watch should be returned, such as this one, that proposes the following code:

gulp.task('watch', function() { return gulp.watch('./public/resources/jsx/project/*.js',['application']) });

I understand that tasks should return, so that other tasks using them as part of their workflow are able to act accordingly to their async nature, but for the special case of a watch task, which is always the last in a list of tasks, there might make sense not to return it, making it possible to have multiple watches.

Does that make sense? Can I safely omit the return from my watch task in order to be able to have multiple instances of gulp.watch in it?


Solution

  • I prefer all task have return statement. Otherwise you can read a false "Finished watch". When task are complex, it is not possible create a single watch for a several pattern of files. In this cases, my solution is based on to create a supergroup task called "watch" that depends on single watches with its return statements.

    gulp.task("watch", [
        "watch-css",
        "watch-js",
        "watch-inject-html"
    ]);
    
    gulp.task("watch-css", function() {
      return gulp.watch(sources.css, ["css"]);
    });
    
    gulp.task("watch-js", function() {
      return gulp.watch(sources.js, ["js"]);
    });
    
    gulp.task("watch-inject-html", function() {
      return gulp.watch(sources.inject, ["inject-html"]);
    });