Grunt js Tutorial – Setup & More

Tweet about this on TwitterShare on LinkedIn0Share on Google+0Share on Reddit0Buffer this pageFlattr the authorEmail this to someonePrint this page

Grunt js Tutorial – Setup & More

This is quick tutorial on Grunt. What it is, how to set it up & utilize its basic features. This tutorial also covers developing a jQuery plugin using Grunt’s scaffolding template.

Contents

What is Grunt?

Grunt is a Task Runner, that will automate repetitive tasks and make you a lazy developer. For instance, you may be using a LESS CSS preprocessor to compile LESS files to CSS. You need to run  less filename.less output.css again and again when you make a change to your LESS file. Or whenever you are distributing your source application to production, you would like to run some sanity tests or minify and bundle assets – Grunt will automate all these for you!

Grunt is a command line tool written in Javascript built on top of Node.js. If you have prior experience in working with Node.js, configuring and using Grunt would not be much of a hassle.

Install Grunt

Grunt as mentioned earlier is a Node Package. So, we need have Node installed to run Grunt.

  • Step 1: Install Node.js. You can follow the tutorial here to get started.
  • Step 2: Install Grunt.js
    • Install grunt
    • Install grunt-cli [command line]
    • Install grunt-init [scaffolding]

Open your terminal/prompt and run

Windows Mac/*nix
npm install -g grunt    sudo npm install -g grunt

-g flag – install grunt globally

Windows Mac/*nix
npm install -g grunt-cli     sudo npm install -g grunt-cli  

Windows Mac/*nix
npm install -g grunt-init       sudo npm install -g grunt-init

Setup/Add Grunt to a Project

Lets create a new folder and name it "grunt-demo". We will use this as our base folder for all the examples.

Now, open terminal/prompt at this path. Lets get started by creating a sample project. We will leverage Grunt’s Project scaffolding tools to generate a project.

For the first example, we will load a simple project with a package.json & gruntfile.js (will tell you more about this file in a moment). Now, for the Grunt scaffolding to work properly, we need to first clone the project template to our local and then we scaffold the project. So, lets run

Windows Mac/*nix
git clone https://github.com/gruntjs/grunt-init-gruntfile.git %USERPROFILE%\.grunt-init\gruntfile   git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile

This will add the grunt file template to the our .grunt-init folder. Now lets scaffold a sample grunt project.

PS: If you are working with an existing project, every time you run a new template command, the old files will be overwritten. So, run the new template command in a new folder, copy paste/integrate files.

Open terminal/prompt and run

grunt-init gruntfile

Where  gruntfile is the name of the template

The template will ask a few questions & you can answer as below.

  • [?] Is the DOM involved in ANY way? (Y/n) Y
  • [?] Will files be concatenated or minified? (Y/n) Y
  • [?] Will you have a package.json file? (Y/n) Y
  • [?] Do you need to make any changes to the above before continuing? (y/N) N

You should see something like this

This will add 2 files, package.json – a file that will store the project dependencies & Gruntfile.js, our task runner config. The above scaffolding template consists of 4 tasks that we can run out of box.

Now, lets setup our project from the package.json. We need to install the project dependencies. For that, we need to run

npm install

Gruntfile walkthrough

All the project dependencies are saved inside the node_modules folder. Open up GruntFile.js & you should see something like this

PS: I have pasted the file here to make sure the walkthrough is the same even after there are changes to the Grunt scaffolding file.

  • Line no 2 : A Nodejs common module syntax to manage node dependencies. More here.
  • Line nos 5-68 : This is the grunt’s initConfig(), that takes in an object. This object consists of the configs needed to run each Grunt task.
  • Line no 7 : Grunt will read our package.json file and pull up all the configs like name, author, package details etc. If you open up the package.json we have got, It will have only the devDependenices & the engines config.
  • Line nos 14-18 : Defines the config object for the concat task. This task will bundle all the js files defined in the src on line no 20 & spit it out to the dest folder defined on line 21. Line 16 consists of the config object to add banners. Banners are comments that appear on top of a file, explaining the contents/license etc.
  • Line nos 24-32 : This is the uglify task, which will take the output of concat task and then minify it. Now you can understand what lines 29-30 do.
  • Line nos 34-55 : This is a jsHint task. This task is a must have for any Javascript developer, who wants to meet the industry standards of writing code. This task will list all the issues in your js code as per coding standards defined here. Line 53 lists the source files to run jsHint on. You can read more about the config object listed on Line nos 35-47 here.
  • Line nos 56-58 : You can read more here.
  • Line nos 59-68 : A watch task is something which runs in the background & keeps looking for changes. If any of the changes are registered in our task list, it will execute the registered tasks. Probably the best task for lazy developers. Line nos 61-63 runs jsHint on Gruntfile.js, incase you change it & Line nos 64-67, defines a few Watch tasks.  Pretty sweet huh? Will dive into this soon.
  • Line nos 72-76 : This will register the available tasks & let Grunt know about the same.
  • Line no 79 : Defines the default task that grunt will run. Tasks will run in the order they are defined.

jQuery Plugin using Grunt

Setup the plugin

Now, lets us create a jQuery plugin using Grunt jQuery scaffolding template. First, we need to add the template to our local grunt-init folder

Windows Mac/*nix
git clone https://github.com/gruntjs/grunt-init-jquery.git %USERPROFILE%\.grunt-init\jquery    git clone https://github.com/gruntjs/grunt-init-jquery.git ~/.grunt-init/jquery

Once this is done, lets scaffold the template in the same folder. Do note that all the files in the grunt-demo folder will be overridden. Since we did not make any changes, we need not worry. Inside the grunt-demo folder, run

grunt-init jquery

This will show an error that there are existing files in this folder & will be overridden. You can either backup these files or delete them manually & run the above command again or use

grunt-init jquery --force

I will use the force flag for this tutorial. When you run the above command, you will be asked a series of question, you can answer them as below (you can update them later too)

  • [?] Project name (grunt-demo) grunt-demo-plugin
  • [?] Project title (Grunt Demo Plugin) Grunt Demo Plugin
  • [?] Description (The best jQuery plugin ever.) A simple jQuery Plugin
  • [?] Version (0.1.0) (hit enter)
  • [?] Project git repository (…) (hit enter)
  • [?] Project homepage (…) (hit enter)
  • [?] Project issues tracker (…) (hit enter)
  • [?] Licenses (MIT) (hit enter)
  • [?] Author name (Arvind Ravulavaru) (hit enter)
  • [?] Author email (…) (hit enter)
  • [?] Author url (…) (hit enter)
  • [?] Required jQuery version (*) *
  • [?] Do you need to make any changes to the above before continuing? (y/N) N

You should see something like as the output

Awesome!! This template provided us with a basic structure to write, test and deploy our plugin. Which redefines the laziness of the developer.

Install the plugin

Now, lets install the dependencies. Run  npm install.

List of files & folders

  • grunt-demo-plugin.jquery.json – consist of the user & project meta data
  • Gruntfile.js – Grunt task config
  • package.json – Dependency manager
  • /libs – Vendor specific files, jQuery, qUnit
  • /node_modules –  dependency files
  • /src –  development folder/ all the plugin files will go here
  • /test – test suits will be written & maintained here.

Since this tutorial is about leveraging Grunt & not jQuery plugin writing, I will use the default plugin present inside /src folder – grunt-demo-plugin.js .

Lets use the default plugin and see some output. Inside the src folder, create a new file & name it ‘index.html‘. Paste the below contents inside it.

This is how we will leverage the plugin. Open index.html in your browser and you should a populated list with ‘Awesome ‘+row number. 

Run Grunt task to build the production version

Now, lets deploy the plugin and make it production ready. Back to terminal/prompt & run

  grunt

If you open the Gruntfile.js, you can see that the default task is configured to jsHint, test (qUnit), clean (the dist folder), concat (all the src js files), uglify (minify the bundles source). A new folder named ‘dist‘ is created in the root. You can see there are 2 versions – minified & unminified. A banner is added to the top of the minified file, which is generated using the template on line no 9 in the Gruntfile.js. You can modify accordingly.

Grunt watch & plugin development

If you open up the Gruntfile.js and at the very end of the initConfig parameter (line no 60), you will see a watch task. This task is super helpful in doing a lot of things. There are 3 sub tasks configured inside this

  • gruntfile : This will monitor the Gruntfile.js & run jsHint to check code quality/fashion
  • src : This will monitor the src folder and all js files inside it. If anything changes, Grunt will trigger the jsHint task & the qUnit task to run the tests again (to check any of the newly written code is breaking a test case. Kinda like a CI (continuous Integration System)).
  • test : This will monitor the js files inside the test folder & run jsHint, the test cases again!

You can add or remove tasks as per your need. For now, we will leave everything as is. Now, lets check out the power of Grunt watch.

Back to terminal/prompt. Run,  grunt watch , & you should see something like this

Lets head to src/grunt-demo-plugin.js and open it up in your favorite editor. Then update line no 15 from   $(this).html('awesome' + i); to   $(this).html('Super Duper awesome ' + i);. And save the file.

Quickly run back to your terminal/prompt, and you should a few lines and a error like this

What just happened? When we changed the code, we broke the plugin! When the plugin was designed it was expected to given a certain output. Now we changed it. Imagine the same happening to a plugin in production. All the people using this will see script error! (Imagine the massacre).

To avoid this, we can either follow a test driven approach as described here. Or, you can go ahead and update the test cases.

For this example, I will update the test cases. Open test/grunt-demo-plugin_test.js in your favorite editor and replace line no 38 from

to

Save the file and you can got back to prompt/terminal & see this output

Awesome right! Now you can run  grunt to build the dist folder again.

You can also run a particular subtask if you need like grunt watch:src. Now, grunt will monitor only the src folder. Any changes done to js files inside test will not reflect.

This is a quick start tutorial on Grunt + jQuery plugin development. You can find more Grunt scaffolding templates here

Grunt, Bootstrap & Test Driven Development

This is a more advanced usage of Grunt. You can check out this post, which will leverage Grunt & TDD to build a responsive website using Bootstrap.


Thanks for reading! Do comment.
@arvindr21

Tweet about this on TwitterShare on LinkedIn0Share on Google+0Share on Reddit0Buffer this pageFlattr the authorEmail this to someonePrint this page
  • Christos D

    Just a quick note that my src/.js file was named jquery.grunt-demo-plugin.js and not grunt-demo-plugin.js
    Great tutorial!

  • Samuel Gong

    Your tutorial should have been in the Grunt official site:)

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Thanks Samuel! :)

    • Charlie Ng

      I totally agree. I have been looking for a clear guideline for grunt but this one is the best!