Using Grunt JavaScript Minification

We will continue from our last blog post on Grunt: using less and css minification to JavaScript minification using a plugin called Uglify.


To begin we will use a linting tool called jshint, to help us in taming our JavaScript with some static code analysis to flags suspicious usage.

We can use the command line npm install for it or we can use the visual studio tool to install

Npm JsHint

Now that we have jshint lets add our grunt task for jshint in our Gruntfile.js

You may realize that something different in our jshint section, there are some ** inside the file name. The pattern of /**/ basically mean traverse through all the children levels of the directory hierarchy, and the *.js means all the file with extension of js. By doing so, our script will always scan through any subdirectory for any future js files we may add.

Lets add a file inside of public/javascripts/ directory and call it myapp.js, our file will look something like this.

When we run our task using TaskRunner in Visual Studio or command line for jshint, we will get back a fail task and some suggestion on our JavaScript.

In order to fix the script jshint already suggest us to use the “===” for compare. Let’s now add another file called myapp2.js and also fix our myapp.js file.

When we rerun our task we should have no more errors.


We will now like to concat the file together and there is yet another plugin for grunt to concat files for us grunt-contrib-concat, as always we can use the npm tool in visual studio or the command line to install it.

And in our Gruntfile.js we will add our concat task

From the script we will see that it will add the bundle.js file into the deploy directory.


and if we open the file, we will see that both scripts are combined into one file.



Lastly, we would like to uglify the file, as in minification of the Javascript files. As always we will install our plugin and modify our Gruntfile.

Our new Gruntfile.js would look like


And now our bundle.min.js file is a minified javascript file (Uglified).



In this post we covered quite an area of grunt where we used multiple plugins to accomplish javascript related task (minification, concat, etc), in the next post we use grunt to automate our testing and clean up task.