- A Gulp plugin takes input a vinyl file object and returns a vinyl file object.
- Vinyl means Virtual file format and It represents metadata object that describes a file.For example path and content are attributes on a Vinyl object.
- In this Demo, “We will learn to develop a custom Gulp plugin”.
- We will be developing a pretty basic Gulp plugin name gulp-letter-type, Which converts the text to either UPPER or LOWER case.
- To demonstrate the Gulp plugin development we have created GulpLetterType project.The following screenshot shows the project structure of GulpLetterType.
- gulp module can be installed using npm install gulp –save-dev command.The following screenshot shows the terminal with gulp installation:-
- through2 module can be installed using npm install through2 –save-dev command.The following screenshot shows the terminal with through2 installation:-
- gulp-util module can be installed using npm install gulp-util –save-dev command.The following screenshot shows the terminal with gulp-util installation:-
- gulp-dest module can be installed using npm install gulp-dest –save-dev command.The following screenshot shows the terminal with gulp-dest installation:-
- The index.js file contains the main code definition for gulp-letter-type plugin.The gulpText method is exported using module.exports property.The code content of index.js file are as follows:-
'use strict'; const PLUGIN_NAME = 'gulp-letter-type'; var through = require('through2'), gutil = require('gulp-util'), PluginError = gutil.PluginError; /** * This method transform the input string to upper/lower case * @param caseType - The transform type upper/lower * @param inputString - The input string * @returns {string} - The transformed string */ var transformText = function(caseType,inputString){ var outString = null; switch(caseType){ case 'uppercase': outString = inputString.toUpperCase(); break; case 'lowercase': outString = inputString.toLowerCase(); break; default: outString = inputString; break; } return outString; }; /** * This method is used for transforming the text to the target type. * @param caseType */ var gulpText = function(caseType) { return through.obj(function (file, enc, callback) { var isBuffer = false, inputString = null, result = null, outBuffer=null; //Empty file and directory not supported if (file === null || file.isDirectory()) { this.push(file); return callback(); } isBuffer = file.isBuffer(); if(isBuffer){ inputString = new String(file.contents); result = transformText(caseType, inputString); outBuffer = new Buffer(result); var aFile = new gutil.File(); aFile.path = file.path; aFile.contents = outBuffer; callback(null,aFile); }else{ this.emit('error', new PluginError(PLUGIN_NAME, 'Only Buffer format is supported')); callback(); } }); }; //Export the Method module.exports = gulpText;
- The demo code can be downloaded from the following link:-
https://github.com/saan1984/GulpLetterType