Using Grunt.js to Merge and Minify JavaScript files in an ASP.NET MVC Application
Posted by: Mahesh Sabnis ,
on 1/25/2015,
in
Category ASP.NET MVC
Abstract: Grunt.js helps to automate client-side tasks like minifying the script files, merging them, performing unit testing etc. In this article, we will demonstrate how to use it in an ASP.NET MVC application.
In an application that involves both server-side (like ASP.NET MVC) and client-side code (like JavaScript, Angular.js etc), a web developer usually ends up with several JavaScript files meant for different functionalities in the application. In current web apps, client-side logic is used to perform complex operations like routing, service calls, validations etc. However as the logic and functionality increases, so does the size of the JavaScript files. Another issue is unit testing this complex functionality. What would help here is if the developer is provided with a ready framework which will automate tasks for minifying the scripts and concatenating large JavaScript files together as well as also help in Unit Testing JavaScript. Enter Grunt.js!
Grunt.js
Grunt.js helps to automate client-side tasks like minifying the script files, merging them, performing unit testing etc. The Grunt ecosystem provides various plugins for performing automated tasks on JavaScript. Since Grunt has dependency on Node.js, Grunt and all its plugins are installed and managed via npm, which is the Node.js package manager. The list and information about Grunt Plugins can be grabbed from here.
To use Grunt.js with an ASP.NET MVC application in Visual Studio 2013, we need to have Grunt Launcher extension for Visual Studio which can be downloaded from here. We also need Grunt.js Task Runner Explorer and NPM/Browser Package Intellisense. This can be downloaded from here. Once Node.js is installed on the machine, we can get the needed plugin using Node.js Command Prompt.
This article will only focus on using Grunt to concatenate and minify JavaScript files.
Implementing Grunt.js in an ASP.NET MVC application
Step 1: To demonstrate Grunt.js to do various tasks as discussed above, we will use an MVC application and perform CRUD operations using Angular.js and ASP.NET WEB API. This application can be downloaded from here. Download the application and open it in Visual Studio.
Step 2: Open Visual Studio 2013 (the article is developed using ultimate edition with Update 3 although you should be able to use the free Visual Studio Community Edition as well). Open the Angular application downloaded from the Step 1. In this project we have Module.js, Service.js and Controller.js JavaScript files in the MyScripts sub-folder of the Scripts folder.
We will be implementing Grunt Tasks for implementing concatenation and minification in this folder path.
Step 3: Now install Grunt for the project. Before installing Grunt.js, since it has a dependency on the Node.js, node must be installed first. Once done, to install Grunt.js, open the Command Prompt of Node.js with Admin rights. Navigate to the Angular project folder from the command prompt. e.g. the Node.Js command prompt with Admin rights is at : C:\Windows\System32
If the Angular project is on F:\MyProjects, then on the Node.js Command prompt, change to the F:\MyProjects folder and run the following commands for installing Grunt.js:
npm install -g grunt-cli
Step 4: In order to use Grunt.js for the project, we need Package.json and Gruntfile.js.
To create Package.json, we need to run the following command on the command prompt.
npm init
This will guide us to specify the information for the package, e.g. name, version, description etc as shown here:

The package.json must have the name and version properties set without which the package will not be installed. These two properties act as a unique identification for the package. Once the required information is entered, the package.json file will be shown on the command prompt:

Copy the Package.json file to the root of the project in visual studio.
Step 5: We also need the Grunt plugin for Cancat and Uglify to run tasks to Concatenate and Minify JavaScript files. To install these plugins, run the following commands in the Node.js command prompt:
npm install grunt-contrib-concat
npm install grunt-contrib-uglify
This will add the node modules in the project so that they can be used for executing the required tasks.
Step 6: In the project, add a new JavaScript file with the name gruntfile.js and add the following code in it:
//S1:
module.exports = function (grunt) {
'use strict';
//S2
grunt.initConfig({
//S3:Open the package.json
pkg: grunt.file.readJSON('package.json'),
//S4:The Concate Task
concat: {
dist: {
options: {
separator: '\n\r',
banner: '/*\nConcatinated JS file \n' +
'Author: Mahesh \n' +
'Created Date: <%= grunt.template.today("yyyy-mm-dd") %>' +
'\n */ \n'
},
// select the files to concatenate
src: ['Scripts/MyScripts/Module.js', 'Scripts/MyScripts/Service.js', 'Scripts/MyScripts/Controller.js'],
// the resulting JS file
dest: 'Scripts/MyScripts/MyAngularLogic.js' }
},
//S5:Task for Minification
uglify: {
options: {
// banner for inserting at the top of the result
banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n', mangle:'false'
},
build: {
src: [''Scripts/MyScripts/MyAngularLogic.js'],
dest: ''Scripts/MyScripts/MyAngularLogic.min.js'
}
}
});
//S6: The Required Plug-Ins whihc will be loaded for Task
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
//S7: the array of tasks
grunt.registerTask('default', ['concat', 'uglify']);
};
The gruntfile.js has some important sections:
- S1: the wrapper function to encapsulate grunt configuration.
- S2: initializes the configuration so that the tasks can be configured.
- S3: Opens and reads the package.json file.
- S4: defines Concat task where the source files are defined using array with src and dest representing the result file.
- S5: Defines task for Minification of the result file of S4.
- S6: Loads the necessary Grunt Plugins modules for performing tasks.
- S7: Registers the array of task to be performed.
Step 7: Build the project. Open the Task Runner Explorer:

This shows all tasks defined in the gruntfile.js.
Step 8: Right-click on the Concat task and select Run:

The output will be displayed as follows:

The file will be generated, but it will be hidden in the MyScripts folder. To view the generated files in the solution explorer, click on Show All Files to generate MyAngularLogic.js file. Right-Click on this file and select the option of Include in the project.
Step 9: Open the Index.cshtml in the Views/Employee and remove the previous references for Module.js, Service.js and Controller.js. Add a reference to the MyAngularLogic.js and run the project to get the following result:

Similarly the Uglify task from the Task Runner Explorer can be executed. This will generate MyAngularLogic.min.js.
Download the entire source code of this article (Github)
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @
maheshdotnet or connect with him on
LinkedIn