Search code examples
gulpgulp-watch

Gulp: how to watch multiple files and perform a task for only the changes files?


I wanna do this thing:

I have a folder with many js files. When I save one of them, I want to save the minified file in other folder.

I got it partially, because my script watch many files and when I change one, all files are copied and minified to the destination folder.

I discover recently that gulp.run is not used anymore.

If someone could help me, I'll be greatful.

I was trying this way:

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

var files_dev = "./_sys/js/private/*.js";
var path_prod = "./_sys/js/public/";

gulp.task('dist-file', function(file) {
    gulp.src(file)
    .pipe(uglify())
    .pipe(gulp.dest(path_prod));
});

gulp.task('default', function() {
    gulp.watch(files_dev).on("change", function(file) {
        gulp.run('dist-file');
    });

Solution

  • dist-file doen't need to be a gulp task, you can make that a function which you can pass the file or glob to process. Also watch is part of gulp now so you shouldn't need gulp-watch.

    var jshint = require('gulp-jshint');
    var uglify = require('gulp-uglify');
    
    var files_dev = "./_sys/js/private/*.js";
    var path_prod = "./_sys/js/public/";
    
    function uglifyFile (file) {
        gulp.src([file])
            .pipe(uglify())
            .pipe(gulp.dest(path_prod));
    }
    
    gulp.task('watch-test', function() {
        gulp.watch(files_dev).on("change", function (event) {
            uglifyFile(event.path);
        });
    });