Blogs about Atlas, Microsoft 365, Teams

[SPFx] Extending Gulp and running tasks in series (or in parallel)

Written by Luis Mañez | Feb 22, 2017 3:50:00 PM

As you may already know, the new SharePoint framework uses Gulp for all the “compilation” tasks: bundle JavaScript files, generate the package file, etc. However, when we have to create our own Gulp tasks, it doesn’t follow the “normal” mechanism of Gulp, so we can’t just add a new “Task” in the “Gulpfile.js”

 

To add a new custom Gulp task, we must go through the SPFx build system, which is defined in the package “@microsoft/sp-build-web”


The build object allows us to call a function “task” and set the definition of our task. It would be something similar to this:



However, imagine that we just want to execute a couple of Tasks, but sequentially. Then, we must use the function “serial” of the build object. The following code snippet runs the tasks “task-1” and “task-2” together and sequentially:


var task1 = build.task("task-1", {
execute: (config) => {
console.log("Fist step");
return new Promise((resolve, reject) => {
const deployFolder = require('./config/prepare-deploy.json');
const folderLocation = `./${deployFolder.deployCdnPath}/**/*.js`;
return gulp.src(folderLocation)
.on('finish', resolve);
});
}
});

var task2 = build.task("task-2", {
execute: (config) => {
console.log("Second step");
return new Promise((resolve, reject) => {
const deployFolder = require('./config/prepare-deploy.json');
const folderLocation = `./${deployFolder.deployCdnPath}/**/*.js`;
return gulp.src(folderLocation)
.on('finish', resolve);
});
}
});

var tasksSerie = build.serial([task1, task2]);

build.task("tasks-serie", serie);

If we run the task, we will see the expected result:



If we want to run the tasks in parallel, the mechanics are the same, but using the function “parallel” of the build.object.

Hope this helps!