Search code examples
node.jsgulpgulp-4chokidar

Run gulp task in chokidar.on() callback


Gulp task 'Copy images' copies ALL image files on the first gulp run. Then, task 'Watch source files' watches the images source folder and imagesWatcher.on('add) intercepts added files. How I can call 'Copy images' from the 'watcher.on()' callback?

Note that gulp task names in camel case are an unwanted limitation. I know that gulp.run was removed in gulp4, however here it could be very handy.

gulp.task('Copy images', () => {
   // ...
})

gulp.task('Watch source files', () => {

    let imagesWatcher = gulp.watch('src/images/**/*.*');
    imagesWatcher.on('add', function(path, stats) {
        // How to call 'Copy images'?
    });
})

Solution

  • Just make your 'Copy images' task into a function (this is the especially nice thing about gulp4) so:

    function Copy_Images() {
      return gulp.src(paths.images.src)
        .pipe(newer(paths.images.dist))
        .pipe(gulp.dest(paths.images.dist));
    }
    
    function Watch_Source_Files() {
        let imagesWatcher = gulp.watch('src/images/**/*.*');
        imagesWatcher.on('add', function(path, stats) {
            // How to call 'Copy images'?
            Copy_Images();
        });
    }
    

    It is that easy with function names. Not sure what you mean by "solution with aliases" in this context.