This quick tutorial will show you how to get started with Gulp and how to create a build script for your static website:
- Gulp installation with NPM
- Project setup
- Copy our HTML files to the output folder
- Concatenate our CSS files
First of all and if you haven’t already done so, you need to install gulp globally:
npm install -g gulp
Then install gulp locally:
npm install --save-dev gulp
At the root of your project, create a file called
gulpfile.js. This is our gulp configuration file; in this file, we will declare all our gulp tasks.
Before we configure our build, we need to agree on a basic project structure. I chose to follow the conventions used by the HTML5 Boilerplate project.
We will have a
src folder that contains all our source files and a
dist folder that contains our final build.
The only thing needed to initialize gulp is to require the gulp node module in the
var gulp = require('gulp');
Once this is done, let’s add our first task.
To define a gulp task, use the following format:
There are many plugins available on npm compatible with the Gulp task runner, but for our first task (copy HTML files to the output directory), the
gulp module is sufficient:
gulp.dest writes all piped files to the folder passed as argument.
The complete code for our task will then look like:
(At this point, I suggest you refactor a bit and use a configuration object to store the strings in a reusable manner.)
What we want here is to simply type
gulp in our command line and have all our gulp tasks executed.
To do this simply add the following line to your gulpfile.js:
What this does is associate an array of gulp tasks (in this example our ‘html’ task) with the default
gulp command. You can add more tasks to that array as we will see next.
But first, save your
gulpfile.js and type
gulp in the command line to check that your html files are copied to the dist directory.
Now that we have our HTML files in the output folder, let’s finish by concatenating all our CSS files into one.
For this, we will need to install a gulp plugin called gulp-concat
npm install --save gulp-concat
Let’s add that plugin to our
gulpfile.js with the rest of our dependencies:
We are now ready to declare our css task. Let’s imagine we want to combine our bootstrap css with our main css file into a file called site.css
What we do here is set our source files as an array of css files, concatenating them and saving the result in a css folder in our dist directory. It is of course possible to add more css files in the src array.
The last step before we can test our build script, consists of adding the css task to our default gulp command:
Modify the last line of your gulpfile.js to be
gulp.task('default', ['html', 'css']);
Run gulp from the command line and voila !
You can check an example of a refactored gulpfile.js for this project here.