Search code examples
gulpbrowser-syncgulp-watchgulp-sass

gulp watch not working when browsersync is added


I try to get a simple workflow running where changes in the sass-file are immediately translated into css and displayed in the browser (using this tutorial: https://css-tricks.com/gulp-for-beginners/) I looked through multiple answers to simliar questions here but couldn't find a solution.

This is my gulpfile:

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


gulp.task('sass', function() {
  return gulp.src('app/**/*.sass') // Gets all files ending with .scss in app/scss
    .pipe(sass())
    .pipe(gulp.dest('app/css'))
    .pipe(browserSync.reload({
    stream: true
  }))
});

var browserSync = require('browser-sync').create();
gulp.task('browserSync', function() {
  browserSync.init({
    server: {
      baseDir: 'app'
    },
  })
})

gulp.task('watch', gulp.series(['browserSync'], ['sass']), function(){
  gulp.watch('app/**/*.sass', gulp.series(['sass']));
})

When I call gulp sass it works perfectly fine. Also, when I remove the browsersync and only use the following code the watching itself works:

gulp.task('watch', function(){
  gulp.watch('app/scss/*.sass', gulp.series(['sass'])); 
})

There must be something wrong with the way the browsersyncing is (not) happening. Can someone help me out? Many thanks in advance!


Solution

  • The following is not in gulp v4 syntax:

    gulp.task('watch', gulp.series(['browserSync'], ['sass']), function(){
      gulp.watch('app/**/*.sass', gulp.series(['sass']));
    })
    

    Move the function into the series arguments. So try this instead:

    gulp.task('watch', gulp.series('browserSync', 'sass', function(){
      gulp.watch('app/**/*.sass', gulp.series('sass'));
    }));
    

    In this way gulp.task() takes 2 arguments instead of 3 - that is the gulp v4 way. That article was written in v3 syntax unfortunately, with a few warnings to change the code for v4.