Automate Your Angularjs Development using gulp and grunt

Introducing Grunt and Gulp

All modern JavaScript applications involve some kind of build process. This might entail preprocessing CSS with Sass/Less/Stylus, concatenating JavaScript files into one, minifying assets, compiling CoffeeScript, and so on. While this can totally be done with ad hoc commands or Bash scripts, there are tools that help you manage these tasks. Another benefit that is sometimes overlooked is these tools typically work on Windows machines and not just Mac and Linux boxes.

I highly encourage taking the time to learn a build tool. It will help clean up your build scripts, make it easier to work on projects you haven’t touched in a while, and make it easier for others to work on your project.

A few tools can help with these tasks; the big two are Grunt and Gulp. Grunt is older than Gulp and is more task-centric. In Grunt, you define in JSON how to do things such as minify JavaScript and compile Sass, and each spits out a file. Gulp is stream-based, and the configuration is written in JavaScript code. Gulp configuration files are way shorter than the Grunt equivalent, and because of its streaming architecture Gulp will run orders of magnitude faster on large projects.

In my opinion, Gulp is a much better tool for asset build tasks and will be the tool used in this book.

Gulp Hello World

To get Gulp up and running, let’s first create a simple task that just outputs “Hello World.” First, install Gulp globally and in the project (you need both) with the following commands:

npm install --global gulp
npm install --save gulp

Next, add the file gulpfile.js to the root of the project. This is a special filename Gulp knows to look for. The contents should be the following:

var gulp = require('gulp')

gulp.task('hello', function () {
  console.log('hello world')

You can now run this hello task:

$ gulp hello
[15:59:03] Using gulpfile ~/src/social/gulpfile.js
[15:59:03] Starting 'hello'...
hello world
[15:59:03] Finished 'hello' after 106 μs

This is the basic form of a Gulp task. You can also have tasks that depend on others by passing in an array:

var gulp = require('gulp')

gulp.task('welcome', function () {
  console.log('welcome to gulp!')

gulp.task('hello', ['welcome'], function () {
  console.log('hello world')

Now if you run the hello task, it will first wait for the welcome task to complete. You can also run the welcome task directly with gulp welcome.

About the author

Deven Rathore

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest