Let us see how to create and test the Gulp tasks in SharePoint Framework solutions.
In my previous article, you can get the basic understanding of Gulp tasks in the SharePoint framework solutions.
As we already know, Gulp tasks and commands help in automating the manual tasks required for solutions. These tasks are defined in the gulpfile.js. By default, some of the tasks or methods are loaded in the Gulp files. These tasks are required for building, bundling, or packaging the solutions. You could see each of these tasks in the previous article.
Let us take a basic example of creating a task for incrementing the version of SPFx solution. This is the manual task required before updating or deploying the SPFx solution onto the SharePoint sites. Here, we will try to automate the same using Gulp task.
The basic syntax for defining the task will be as follows.
- build.task(taskname, custommethod());
The custom method will contain the steps for updating the version of the solution. The arguments can be passed to the method using the commands. So, for example, to call or execute the above task, the command used will be -
- gulp taskname --argument1
Likewise, any number of arguments can be passed.
The below code sample shows gulpfile.js file which has the steps required for updating the version number using Gulp task. The task name is “update-spfx-solution”. The argument passed will be --updateVersion. This argument is to execute and validate the version updating steps only.
- 'use strict';
- const gulp = require('gulp');
- const build = require('@microsoft/sp-build-web');
-
- const fs = require('fs');
- build.task('update-spfx-solution', {
- execute: (config) => {
- return new Promise((resolve, reject) => {
-
- if(config.args['updateVersion']){
-
- let json = JSON.parse(fs.readFileSync('./config/package-solution.json'));
- var majorVersion = parseInt(json.solution.version.split('.')[0]);
- majorVersion++;
- json.solution.version = majorVersion + '.0.0.0';
- fs.writeFileSync('./config/package-solution.json', JSON.stringify(json));
- resolve();
- }
-
- });
- }
- });
-
- build.initialize(gulp);
In the above sample,
- Argument is validated. (Command should contain the updateVersion flag)
- Package-solution.json file is read using fs package.
- The file is parsed as JSON and the version number is retrieved.
- Version number is incremented and the same is updated by stringifying the JSON.
The following snapshot shows the package-solution.json file before executing the command.
The following snapshot shows the command executed.
The following snapshot shows the package-solution.json file after executing the command
Summary
Thus, you have learned to create custom Gulp tasks which help in automating the manual tasks in SharePoint framework solutions.