Getting started with Grunt on Windows 7

Let’s get up and running with Grunt now. I will be using the uglify plugin as an example here. We will combine and minify a directory of js files. We will also set a source map for our combined min file so when we are attempting to debug issues on our deployment, we will be able to see the actual line of code causing the issue. If you do not already know, source maps allow us to keep track of all the files that have been combined and the actual line numbers in those files so when an error is detected in our js, we can find the un-combined/minified line of code that we will need to correct.

First let’s install the grunt CLI globally.
$ npm install -g grunt-cli

We will need two files in our root for Grunt. The first is a package.json file. This will contain some information about your project and all its dev dependencies. A sample package.json is below.
//**********file contents********************
{
“name”: “my-project-name”,
“version”: “0.1.0”,
“devDependencies”: {
“grunt-cli”: “~0.1.13”
}
}
//**********file contents********************
Update the above file to include grunt as a dev dependency with the below command.
$ npm install grunt –save-dev

Next, we will install the grunt plugins needed for the task we wish to build.
$ npm install grunt-contrib-uglify –save-dev

The second file will be our Gruntfile.js. The file we will need for our purposes is below.
//**********file contents********************
module.exports = function(grunt) {

// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON(‘package.json’),
uglify: {
options: {
banner: ‘/*! */\n’,
sourceMap: true
},
build: {
src: ‘src/Matrix.Web/Content/Scripts/*.js’,
dest: ‘build/combined-uglify.min.js’
}
}
});
//**********file contents********************

// Load the plugin that provides the “uglify” task.
grunt.loadNpmTasks(‘grunt-contrib-uglify’);

// Default task(s).
grunt.registerTask(‘default’, [‘uglify’]);

};

The below wrapper code is where we must put all code we wish to be executed by Grunt.
module.exports = function(grunt) {
//place code here
};

Next, we have the initial configuration needed for our tasks. We are currently only listing uglify here because it is the only plugin we will be using today. We are also setting an option called sourceMap to true. This will tell uglify to create a source map file for our combined min js file so we can better debug our application.

After the configuration, we need to load in our grunt plugins. Finally, we define our tasks and what will execute when we run them.

Here, we are defining the default task and telling it when we run it, we want to run our uglify plugin. To execute the default task, we need only run grunt.
$ grunt

Leave a comment