Running Gulp tasks in series
I ran into a problem today for minifying and concatenating for a CSS library, as I wanted the tasks to run in sequence.
This Gulp recipe for running tasks in series gives us a nice example of returning streams from Gulp tasks, enabling tasks to be run one ofter the other.
In the example templates and styles will be processed in parallel. The clean task will be guaranteed to complete before either start..
var gulp = require('gulp');
var del = require('del');
gulp.task('clean', function(cb) {
del(['output'], cb);
});
gulp.task('templates', ['clean'], function() {
var stream = gulp.src(['src/templates/*.hbs'])
.pipe(gulp.dest('output/templates/'));
return stream;
});
gulp.task('styles', ['clean'], function() {
var stream = gulp.src(['src/styles/app.less'])
.pipe(gulp.dest('output/css/app.css'));
return stream;
});
gulp.task('build', ['templates', 'styles']);
gulp.task('default', ['build']);
This is how tasks are depend upon in Gulp. In this example task two depends on task one, so running Gulp two
would run both tasks
gulp.task('one', function(cb) {
// do stuff
});
gulp.task('two', ['one'], function() {
// task 'one' is done now
});
I used this in a simple Gulpfile for a CSS library recently
var gulp = require('gulp'),
less = require('gulp-less'),
concatCss = require('gulp-concat-css'),
minify = require('gulp-minify-css'),
rename = require('gulp-rename');
gulp.task('less', function() {
var stream = gulp.src('less/*.less')
.pipe(less())
.pipe(gulp.dest('./css'));
return stream;
});
gulp.task('concatCss', ['less'], function (cb) {
var stream = gulp.src('css/**/*.css')
.pipe(concatCss("styles.css"))
.pipe(gulp.dest('.'));
return stream;
});
gulp.task('minify', ['concatCss'], function (cb) {
var stream = gulp.src('styles.css')
.pipe(minify({keepBreaks: true}))
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('./'));
return stream;
});
// default gulp task
gulp.task('default', ['minify'], function() {
});
The Gulpfile has less
concatCss
and minify
tasks and running the default task I kick off the minify task which depends on concat, and concat depends on less, so these tasks will run in the order top to bottom.