Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Setting up grunt to automate repetitive tasks in javascript applications

You have prob­a­bly heard about grunt by now. Maybe you are crys­tal clear on what it is, maybe its still hazy. In this post, we will go on a roller coaster ride and help you under­stand what grunt is so that you can start using it in your projects right away.

So, what is grunt used for?

For automat­ing tasks like bundling, mini­fy­ing, jsh­int­ing etc etc.

What are the dif­fer­ent things in grunt?

  • A com­mand line util­ity for run­ning grunt (npm install –g grunt-cli)
  • A set of instal­lable plu­g­ins (to be spec­i­fied as devDe­pen­den­cies in your package.json). Each plu­gin pro­vides you with ‘Tasks’ that once con­fig­ured can be run from your project’s root directory.
  • A task con­fig­u­ra­tion file (Gruntfile.js) in your project’s root direc­tory that con­tains the con­fig­u­ra­tion for each task that you have installed.

Learn by example

For the pur­pose of this post, we will try setup grunt to do the fol­low­ing things
– Run jshint on all of your source files
– Con­cate­nate all your source files into a bundle.js
– Run jshint on your bundle

To do this, we will need to install 2 grunt plu­g­ins that pro­vide us with these tasks.

Now our prob­lem state­ment changes to…

How to run the ‘jshint’ and ‘con­cat’ tasks on the files that I want?

You can install them by run­ning the fol­low­ing com­mands from your root dire­cotry
npm install grunt-contrib-jshint –save-dev
npm install grunt-contrib-concat –save-dev

Set­ting up the grunt tasks

A Grunt­file is the heart and soul of your grunt enabled appli­ca­tion. It is noth­ing more than a mod­ule that exports one func­tion that takes one argu­ment — the grunt object.

Using this grunt object you need to do a cou­ple of things:
– call the init­Con­fig pass­ing it an object that con­tains the con­fig­u­ra­tion for each task that you want to run.
– Load the npm mod­ules that have the capa­bil­ity to run those tasks.

Once you cre­ate your grunt file, your direc­tory struc­ture should look like this.

Now, for each grunt task, you group together con­fig­u­ra­tion under a ‘tar­get’. aka. A grunt ‘tar­get’ is a fany name for a group of con­fig­u­ra­tion para­me­ters under a sin­gle task. A task can have many such groups/targets.

For exam­ple

Once all of this is done, you can exe­cute grunt tasks from your project root as follows.

Thats as sim­ple as it gets to start using grunt for your projects.

Ryan Sukale

Ryan is just a regular guy next door trying to manage his life and finances.

You may also like...