Ever wondered how to run task one after another (or in sequence) inside a gulp.watch()?. Well, now I’ve brought the solution to you!.

Imagine you have two different task but you need to run the 1) BEFORE the 2) and the cannot run simultaneously. Eg:

  1. One for compile your SASS into beautifull CSS
  2. And another for reloading your browser so you can see your changes instantly

If you wanna follow this example, please install the next npm packages

npm install gulp gulp-livereload gulp-sass run-sequence --save-dev

Of course, you need to have previously installed Node.js

1) Compile your SASS

Maybe your task could look something like this

var gulp = require('gulp'); 
var livereload = require('gulp-livereload');
var sass = require('gulp-sass');
gulp.task('compile-sass', function () { 
return gulp.src( './scss/**/*.scss' )
.pipe(sass({ includePaths: SASS.FILES })
.on('error', sass.logError))
.pipe(gulp.dest( './css' ))
.pipe(livereload());
});

2) Reload your browser

Using gulp-livereload this should be as simple as:

var livereload = require('gulp-livereload'); 
gulp.task('reload', function() { 
return livereload.reload();
});

It’s important to also include this script in your <head> tag. (35729 it’s de default port for livereload)

<script src=”//localhost:35729/livereload.js?snipver=1" type=”text/javascript”></script>

3) Running things synchronously

gulp.task('watch', function () { 
livereload.listen(); // Listening for changes
gulp.watch('./*.scss', function(event){
// Compile SASS and Reload, in that order
runSequence('compile-sass', 'reload');
});
});

Using runsequence() inside the callback of the .task() function you can run pre-defined task in sequence.

For more info about running some task in parallel or not, check the run-sequence documentation on the npm repository.

Resources:

  • This question in Stackoverflow.
  • My personal experience and nerdyness

Originally published at blog.diegomarmol.com.ar on May 17, 2016.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.