Search code examples
gulpgulp-watchgulp-sass

Compile gulp sass into the serve task


I make this gulp tasks: sass, serve, watch, but I'm trying to run gulp sass when the gulp watch into the gulp serve is activate but it's not work.

I need when I do a change into the sass file, this compile and show in realtime in the browser.

Any help ?

var gulp = require('gulp'),
    browserSync = require('browser-sync'),
    postcss = require('gulp-postcss'),
    autoprefixer = require('autoprefixer'),
    sass = require('gulp-sass');

gulp.task('serve', function() {
  browserSync.init({
    notify: false,
    port: 3005,
    server: {
      baseDir: ["app"],
      routes: {
        '/bower_components': 'bower_components'
      }
    }
  })

  gulp.watch(['app/**/*.*']).on('change', browserSync.reload);
});

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

  var processors = [
    autoprefixer({ browsers: ['last 2 versions']})
  ];

  return gulp.src('./app/sass/*.scss')
    .pipe(sass().on('error',sass.logError))
    .pipe(postcss(processors))
    .pipe(gulp.dest('./app/css'));
});

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

gulp.task('default', ['sass']);

Solution

  • Adding .pipe(browserSync.reload({stream: true})) to your sass task pipe should make browsersync reload only the compiled css.

    Here's an example of your gulp task

    gulp.task('sass', function() {
        var processors = [
            autoprefixer({ browsers: ['last 2 versions']})
        ];
    
        return gulp.src('./app/sass/*.scss')
            .pipe(sass().on('error',sass.logError))
            .pipe(postcss(processors))
            .pipe(gulp.dest('./app/css'))
            .pipe(browserSync.reload({stream: true}));
    });