Search code examples
javascriptgulpgulp-watch

Gulp watch only detects the first change


I am working on gulp and implementing watch functionality. But the gulp watch detects the changes only for the first time.

I want to write the code so that it detects the changes in CSS and JS files and performs minification and concatenation on the development environment.

I am using the following code:

var gulp = require('gulp');
var concat = require('gulp-concat');
var clean_css = require('gulp-clean-css');
var uglify = require('gulp-uglify');

gulp.task('style', function(){
    gulp.src(['assets/css/style.css', 'assets/css/custom.css'])
        .pipe(concat('build.min.css'))
        .pipe(clean_css())
        .pipe(gulp.dest('assets/build'));
});

gulp.task('script', function(){
    gulp.src(['assets/js/jquery.js', 'assets/js/custom.js'])
        .pipe(concat('build.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('assets/build'));
});

gulp.task('watch', function(){
    gulp.watch('assets/css/*.css', gulp.series('style') );
    gulp.watch('assets/js/*.js', gulp.series('script'));
});

Solution

  • This is probably because gulp does not know the task has finished the first time so it will not re-start the task again when you modify a file next. This can be solved just by adding return statements to your tasks:

    gulp.task('style', function(){
      return gulp.src(['assets/css/style.css', 'assets/css/custom.css'])
        .pipe(concat('build.min.css'))
        .pipe(clean_css())
        .pipe(gulp.dest('assets/build'));
    });
    
    gulp.task('script', function(){
      return gulp.src(['assets/js/jquery.js', 'assets/js/custom.js'])
        .pipe(concat('build.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('assets/build'));
    });