Search code examples
node.jssassgulp

gulp combining tasks into default command


How to I go about combining my styles task my browser-sync and my watch task into one gulp default command?

Here is what I have so far.

var gulp = require("gulp");
var sass = require("gulp-sass");
var browserSync = require("browser-sync").create();

gulp.task("styles", function() {
  gulp
    .src("sass/**/*.scss")
    .pipe(sass().on("error", sass.logError))
    .pipe(gulp.dest("./css/"));
});

// Static server
gulp.task("browser-sync", function() {
  browserSync.init({
    server: {
      baseDir: "./"
    }
  });
});

//Watch task
gulp.task("default", function() {
  gulp.watch("sass/**/*.scss", gulp.series("styles"));
});

I have also tried this from the browser-sync documentation but it gives me the error AssertionError [ERR_ASSERTION]: Task function must be specified With the same variables at the top.

gulp.task("serve", ["sass"], function() {
  browserSync.init({
    server: "./"
  });

  gulp.watch("/sass/*.scss", ["sass"]);
  gulp.watch("/*.html").on("change", browserSync.reload);
});

// Compile sass into CSS & auto-inject into browsers
gulp.task("sass", function() {
  return gulp
    .src("/scss/*.scss")
    .pipe(sass())
    .pipe(gulp.dest("/css"))
    .pipe(browserSync.stream());
});

gulp.task("default", ["serve"]);

Solution

  • I'm guessing you're using gulp 4 which handles dependent tasks a bit differently, which is why you're getting an error.

    If indeed you are using gulp 4, try out the official recipe:

    var gulp = require('gulp');
    var sass = require('gulp-sass');
    var browserSync = require('browser-sync');
    
    gulp.task('sass', function() {
      return gulp.src('sass/**/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('./css/')) //removed semicolon
        .pipe(browserSync.reload({ stream:true }));
    });
    
    // watch Sass files for changes, run the Sass preprocessor with the 'sass' task and reload
    gulp.task('serve', gulp.series('sass', function() {
      browserSync({
        server: {
          baseDir: './'
        }
      });
    
      gulp.watch('sass/**/*.scss', gulp.series('sass'));
    }));