Search code examples
javascriptgulp

Gulp watch keeps running after I save the file


I installed gulp to minify my JS file. When I run gulp watch the watcher is waiting for the file to change, so that's good. However, when I modify the file and save it, the watch task is not fired only once, but it keeps getting fired, and it's not stopping. I have to manually stop the task by hitting ctrl + c.

This is my gulpfile.js file:

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

gulp.task('min-js', function() {
    return gulp.src('lib/app.js')
        .pipe(minify({
            ext: {
                min: '.min.js'
            },
            ignoreFiles: ['-min.js']
        }))
        .pipe(gulp.dest('lib'))
});

gulp.task('watch', function(){
  gulp.watch('lib/app.js', gulp.parallel('min-js'));
  // Other watchers
});

gulp.task('default', gulp.parallel('min-js', 'watch'));

Solution

  • gulp-minify outputs the source files in addition to the minified files.

    See the documentation here.

    Since the output is being piped into the same directory as the input, lib, the watcher sees that the input file was overwritten, and triggers again. This causes an infinite loop of watcher triggering minification.

    Solutions:

    1. Change the output directory to be different from the input directory.
    2. Use the noSource option on gulp-minify to prevent the output of source files.