Gulp: how to compose tasks sequentially?

I will need to compose gulp tasks, sequentially processing different sources, since there are dependencies between them.

Based on the documentation, this should be done by merging threads, but I don't see a way to enforce and streamline them.

What is the correct way to simulate this in gulp 3?

I usually use functions as containers for individual build steps, and then call them from the build and view tasks:

function buildModule(module) { var streams = []; // step one streams.push( gulp.src(path.join('./modules', module, '*.js')) // ... series of chained calls ); // step two streams.push( gulp.src([TMP, ...]) // generate target also using some of the files from step one ); return eventStream.merge(streams); } gulp.task('build:A', [], function () { return buildModule('A'); }); gulp.task('watch:buildModule', [], function () { gulp.watch('./modules/**/*.js', function (event) { if (event.type === 'changed') { return buildModule(path.basename(path.dirname(event.path))); } }); }); gulp.task('default', ['watch:buildModule'], function () {}); 
+7
javascript gulp
source share
2 answers

There are basically three ways to do this.

1. Definition of dependent tasks

Gulp allows developers to define dependent tasks by passing an array of task names as second arguments:

 gulp.task('concat', function () { // ... }); gulp.task('uglify', ['concat'], function () { // ... }); gulp.task('test', ['uglify'], function () { // ... }); // Whenever you pass an array of tasks each of them will run in parallel. // In this case, however, they will run sequentially because they depend on each other gulp.task('build', ['concat', 'uglify', 'test']); 

2. Using the execution sequence

You can also use run-sequence to sequentially run an array of tasks:

 var runSequence = require('run-sequence'); gulp.task('build', function (cb) { runSequence('concat', 'uglify', 'test', cb); }); 

3. Using lazypipe

Although Lazypipe is a library for creating reusable pipelines, you can somehow use it to create sequential tasks. For example:

 var preBuildPipe = lazypipe().pipe(jshint); var buildPipe = lazypipe().pipe(concat).pipe(uglify); var postBuildPipe = lazypipe().pipe(karma); gulp.task('default', function () { return gulp.src('**/*.js') .pipe(preBuildPipe) .pipe(buildPipe) .pipe(postBuildPipe) .pipe(gulp.dest('dist')); }); 
+15
source share

This small module can help: stream-series .

Just replace eventStream.merge(streams) with:

 var series = require('stream-series'); // ... return series(streams); 
+3
source share

All Articles