May 01
2013
Minification using Grunt/Uglify
Assuming you have npm installed, run the following commands in the terminal. Navigate to the project where you want to use Grunt.
$ npm install -g grunt-cli
$ pwd // im in /usr/home/myname/workspace
$ mkdir test-grunt // our test grunt project directory
$ cd test-grunt
$ npm init // it will ask some questions to create a package.json file in this directory
add a directory called scripts/src and put some js file in it, one or more
create a file called Gruntfile.js in the directory where your package.json resides
copy-paste the following code in your Gruntfile.js
module.exports = function(grunt){
grunt.initConfig({
pkg : grunt.file.readJSON('package.json'),
// tasks here
uglify : {
compress : {
// file array format.. also see compact format in the resource given below
files : [
{
// flag to indicate grunt to expand the options given below it
expand : true,
// path relative to which the regex in src will be matched
cwd : 'scripts/src',
// array of paths relative to cwd, specified above
src : ['*.js'],
// will create a dest directory inside scripts and place the min files there
dest : 'scripts/dest/',
// extension of the minified files.. you could have something like .prod.js, for production versions
ext : '.min.js'
}
],
options : {
// really helpful during development, to see how less useful optimizing the uncompressed file actually is !
// shows the size of original js files, minified and also gzipped files
report : 'gzip',
// to help optimize the varibale names and stuff like that
compress : true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('default', ['uglify']);
};
run the following command to tell grunt that you task is dependent on a plugin called uglify..
npm install grunt-contrib-uglify --save-dev
this option will help add the dependecy parameter in the package.json file. Checkout package.json after you run this commnd and you will see the dependency added, along with compatible version number.
now run the following:
$ grunt // will show a verbose result and finally a report indicating the sizes of original, minified and gzipped versions as requested.
In the next post, I’ll write how to make use of this minified file and setup apache to compress it.
Resources :
Getting Started with Grunt and the Further Reading section of it
UglifyJS plugin for Grunt
