Gulp: JavaScript build automation
Posted 16 July 2016
What is it?
Gulp is a Node npm package that allows for automation of tasks in order to remove common time-consuming processes from developer’s workflow. Gulp is platform independent with plugins/integration available for all popular IDEs,. It runs within the JavaScript runtime environment Node.js allowing for easy use of packages from the npm ecosystem which is the “largest ecosystem of open-source libraries in the world”. Furthermore, there are many open-source packages created for integration with Gulp with the prefix ‘gulp-’.
Common tasks automated with Gulp include concatenation, minification, live reloading page on code changes and running tests/code coverage. Using a build system like Gulp is a must if we want to use more advanced language features which require compiling/transpiling such as SASS/LESS (CSS preprocessors) or TypeScript/Babel/Browserify (JavaScript language extensions). See the full list of Gulp recipes of use cases with code examples.
Installation
Gulp requires installing Node and npm. Once installed and the npm command is available in your command line install the Gulp command line interface:
npm install -g gulp-cli
To install Gulp as a developer dependency within an npm project navigate to the project's root directory and initialise an empty npm 'package.json' file:
npm init
Then install Gulp as a developer dependency:
npm install --save-dev gulp
Gulp tasks are contained in a file called gulpfile.js
located in the root folder of the project. Here is an example with an empty default task:
var gulp = require('gulp');
gulp.task('default', function() {
// default task code goes here
});
Finally the default gulp task can be run and nothing will happen:
gulp
Tasks
When no task name is given to the gulp command the ‘default’ task is executed. Tasks can also be created with names:
var gulp = require('gulp');
gulp.task('css', function() {
// do something to the CSS
});
And executed individually from the command line:
gulp css
In addition, tasks can depend on other tasks:
var gulp = require('gulp');
gulp.task('build', ['css', 'js'], function() {
console.log('Build complete!');
});
gulp.task('css', function() {
// do something to the CSS
});
gulp.task('js', function() {
// do something with the JavaScript
});
Plugins
The open source plugins for Gulp available are what makes it so powerful. A useful trick for managing loading Gulp plugins is the plugin gulp-load-plugins.
npm install --save-dev gulp-load-plugins
Then you can add the following to your gulpfile.js:
var gulp = require('gulp');
var gulpLoadPlugins = require('gulp-load-plugins');
var plugins = gulpLoadPlugins();
The plugins object will now contain all Gulp plugins which are installed as dev dependencies in your ‘package.json’ (ie. all ‘--save-dev’ plugins which begin with ‘gulp-’). For example if you had the ‘gulp-concat’ plugin installed for concatenating files, it would be accessible via the plugins.concat()
function.