Search code examples
javascriptgulp

How to watch sass and javascript at the same time in gulp 4


I am trying to convert my sass to compressed-css and javascript to uglified-js. And watch both scss and js changes

my code is working but when I tried saving a js file, it goes into a unstoppable loop.

Here is my code:

var gulp = require('gulp');
var sass = require('gulp-sass');    
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');

gulp.task('sass', function(done){

    gulp.src('public/sass/**/*.scss')
      .pipe(sass({outputStyle: 'compressed'})) // Using gulp-sass
      .pipe(gulp.dest('public/stylesheets'))

      done();
  });

gulp.task('scripts', function(done){

    gulp.src('public/javascripts/**/*.js')
        .pipe(concat('scripts.js'))
        .pipe(uglify())
        .pipe(gulp.dest('public/javascripts'))

        done();
});


  gulp.task('watch', function(){
        //I made .scss and .js into an array so they will both be watched
    gulp.watch(['public/sass/**/*.scss', 'public/javascripts/**/*.js' ], gulp.series('sass', 'scripts', function(done) {


        done();
      }))
  })

Now when I run gulp watch it is working but then when I save a js file, I goes into a saving loop, It's saves and saves and saves nonstop.

I have made scss work with this code

 gulp.task('watch', function(){
    gulp.watch('public/sass/**/*.scss', gulp.series('sass', 'scripts', function(done) {


        done();
      }))
  })

But I have no idea how I can make .js files be watched.

I searched google for possible answer but only find the older version solution. Is there a way I can do this with gulp4?

  • I also tried gulp.parallel but it still looped

Please help. Thanks


Solution

  • Your original code:

    gulp.task('watch', function(){
            //I made .scss and .js into an array so they will both be watched
        gulp.watch(['public/sass/**/*.scss', 'public/javascripts/**/*.js' ], gulp.series('sass', 'scripts', function(done) {
    
        done();
        }))
    })
    

    should be

    gulp.task('watch', function(done){
    
        // added done above too
    
        gulp.watch('public/sass/**/*.scss', gulp.series('sass') )
        gulp.watch('public/javascripts/**/*.js', gulp.series('scripts') )
        done();
    })
    

    Your code triggers both 'sass' and 'scripts' tasks when either a scss or js file is modified, which is wasteful (for example, the 'sass' task will start when a js file is altered but not actually do anything with that js file but will needlessly run the sass re-compilation although no scss file changed).