Search code examples
javascriptgulpgulp-watch

Gulp watch for file additions and deletions


I have a Gulp task, wire that injects the application JavaScript into index.html.

I'd like to have another Gulp task, watch, that watches for changes on JavaScript files, and runs wire if there is a new file added or an existing file removed.

The tasks below accomplish this process:

gulp.task('wire', function () {
    var injectScripts = gulp.src('src/app/**/*.js');

    return gulp.src(path.join(conf.paths.base, 'index.html'))
        .pipe($.inject(injectScripts, {}))
        .pipe(gulp.dest(path.join(conf.paths.base)));
});

gulp.task('watch', function () {
    var watcher = gulp.watch(path.join(conf.paths.src, '/app/**/*.js'));

    watcher.on('change', function (ev) {
        if (ev.type === 'added' || ev.type === 'deleted') {
            gulp.run('wire');
        }
    });
});

Unfortunately, it looks like this method is deprecated. When running it, I get deprecation notices in the console:

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

When I swap out gulp.run() with gulp.start() (which seems to have little to no documentation), the file changes to index.html are lagged (they take several minutes to go through, which is strange).

Obviously I could change my watch task to just run wire whenever a JavaScript file changes and not filter based on the event type, but it seems like a huge waste of unnecessary processing to run wire when an existing file changes:

gulp.watch('src/app/**/*.js', ['wire']);

What is the recommended Gulp strategy to do this?


Solution

  • Take a look at the long-running discussion of this in this link

    var wire = function() {
      var injectScripts = gulp.src('src/app/**/*.js');
    
      return gulp.src(path.join(conf.paths.base, 'index.html'))
          .pipe($.inject(injectScripts, {}))
          .pipe(gulp.dest(path.join(conf.paths.base)));
    };
    
    gulp.task('wire', function () {
        wire();
    });
    
    gulp.task('watch', function () {
        var watcher = gulp.watch(path.join(conf.paths.src, '/app/**/*.js'));
    
        watcher.on('change', function (ev) {
            if (ev.type === 'added' || ev.type === 'deleted') {
                wire();            
            }
        });
    });