Version 1.0 is nearing for our Landboss project, and we’re since we’re at the final stretch a lot of our work is general optimization and code cleanup. As part of this we needed a way to compress (or more precisely, minify) our javascript/css files. One of the simpilest ways is to use the YUI Compressor which is a java application that will minify both javascript and CSS files. It can be run from the command line easy enough, but we had several reasons why we didn’t want to just run it against our files and commit them to our code repository.
- Since landboss is still an active project we would then have to maintain both a human-readable and a minified copy in our repository, which is just begging for someone to forget to commit one version and screw everything up
- Everyone would have to install and use the YUI compressor on their own machines, a real pain to set up.
- We have many, many JS/CSS files so we’d have to make a batch file or something or else it would be unworkable to manually run the compressor against them all.
My first soluton was to write an IHttpHandler for ASP.NET that would minify JS/CSS files at runtime. While that works well and is super-cool it requires some IIS fiddling and since some of our JS/CSS files were quite large it would significantly increase the request time for the first user before it cached the minified files. It was still acceptable, but since we use NAnt to create our release builds for deployment it occured to me we could just do it at build time. Not necessarily at each developers’ build time, but at the release build time (so maybe “deployment time” is better? *shrug*). Anyway once I installed the JRE and YUI Compressor on the build server it was a simple task to write a NAnt target that would run the compressor on all JS/CSS files:
A little explanation: the “foreach” tasks performs the “do” tasks for each item in the “in” collection. In this case our “in” is a collection of files in our output directory and will perform the task(s) on all files with either a .css or .js extension. It runs the command line “java” command with the command line arguments needed to run the compressor. ${filename} is listed as the “property” attribute of our
But, once this is set up, any site that gets built with the build script will have their JS/CSS files automatically compressed and won’t require any run-time resources. Tanoshinde kudasai!