March 28th, 2011

Minifying Javascript with Jake and UglifyJS

One of the first things you'll want to do when deploying your shiny new HTML5 app is minify all your Javascript. It saves space, and depending on the minifier, will perform some neat optimizations on your code.

Recently I had to do this on one of my apps, and I didn't feel like running my files through a minifier by hand; that's what build scripts are for! So, here is how I did it.

The minifier I've chosen to use is UglifyJS, and the build tool is Jake. You can install both via npm ('uglify-js' and 'jake' are the module names).

This is the Jakefile that I use to minify all my client-side Javascript into a file called all.js:

var fs = require('fs');
var sys = require('sys');
var uglify = require('uglify-js');

desc('Uglify JS');
task('minify', [], function(params) {
  var files = ['jquery-1.5.min.js',
               'jquery.easing.1.3.js',
               'jquery.boxy.js',
               'jquery.form.js',
               'date.js',
               'util.js',
               'layout.js'];

  var all = '';
  files.forEach(function(file, i) {
    if (file.match(/^.*js$/)) {
      all += fs.readFileSync('public/js/'+file).toString();
    }
  });

  var ast = uglify.parser.parse(all);
  var out = fs.openSync('public/js/all.js', 'w+');
  ast = uglify.uglify.ast_mangle(ast);
  ast = uglify.uglify.ast_squeeze(ast);
  fs.writeSync(out, uglify.uglify.gen_code(ast));
});

Use Jake the same way you would use make, just run `jake minify`.