atlas by clearpeople

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

  

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”

 

SharePoint framwork Gulp 1

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”

SharePoint framwork Gulp 2

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

SharePoint framwork Gulp 4

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:

SharePoint framwork Gulp 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!

Author bio

Luis Mañez

Luis Mañez

Luis is Atlas Chief Architect. He is also a Microsoft 365 Development MVP and SharePoint and Cloud Solutions architect. "I help find the best technical designs to meet client needs and act as tech lead to build great solutions. I have fun with some R&D tasks, always trying to improve our tools and processes, and I often help the Microsoft community as a blogger and speaker, contributing to open-source projects."

View all articles by this author View all articles by this author

Get our latest posts in your inbox