During the last couple of weeks there’s been a lot of buzz around gulp, which is a build system similar to Grunt but with a different approach. gulp’s main feature is that it’s using streams for all of the processing. This generally means better flow control and thus no need for creating temporary files and folders when you’re running different tasks.
I won’t dwell into how streams work, but if you want to learn more about streams in Node.js work I encourage you to read the “Stream handbook”. If you want to learn more about standard streams, try “Dig Into Unix: Standard Streams”.
gulp is at its core very simple and consists of just a few functions:
env. This guide will focus on the first five
of those. Take a look at the gulp API
you want more information on each individual function.
To define a build task you use
To read your source files you use
To write your files you use
To run different tasks from inside another task you use
To watch your files for changes you use
gulp we first need to install it globally:
We’ll then add it as a dependency in our project’s
Since we’re going to lint and test our code we’ll also install
Now let’s create a file called
add.js and save it in a folder called
We’ll also need some tests. Create a file called
add.test.js in a folder
Next we’ll create a file called
gulpfile.js at the root of our project and
require our dependencies:
Then we’ll add our
The reason we use
return in our tasks is to make sure that the task finishes
completely before the next one gets executed.
Lastly we’ll create our
default task. We’ll first add our
tasks as dependencies (since we also want to run them before the
starts) and then use both
gulp.watch() for running them
automatically whenever we update a file:
This is how our
gulpfile.js looks now:
Now, open up a terminal and run
gulp. The output should look similar to this:
That’s it. Until you stop the
default task both the
will run whenever you modify a file in the
Why use gulp?
gulp’s introduction slides brings up a couple of valid reasons for using it in favor of other build systems. You’re writing actual code where you can use Node.js’ standard library in a simple way. All plugins should focus on doing one thing and one thing only, as stated in the guidelines on “writing a gulp plugin”.
In the end, like always, it’s just a matter of preference.