Coding Tips & Tricks

Minify Javascript files automatically with a T4 template

After my last post, I decided to dive a little more into T4 templates and learn more about them. After some goofing around, I decided to write a template that would minify js files automatically using the Yahoo YUI compressor for .net - http://www.codeplex.com/YUICompressor.

T4 is a code generator that is built into Visual Studio, so you can start playing straight away.

In order to use my T4 template, you simply need to download a copy of YUI compressor and add a reference in your project. You will also need to add a reference to the EcmaScript.Net.modified dll.

Once that is done, drop the template into the same folder as your js files. The template will automatically run once its dropped into the folder and it will spit out the minified version of your js. If you need to run it again after making any changes just right click and choose run custom tool, and it will update the files.

I know that there are a few other ways of minifying your javascript files, but for me this seemed like a nice simple, slick way to do it. Plus I also learnt a little about T4 templates. This is only the tip of the iceberg when it comes to T4 templates, and I reckon there is loads more power that can be harnessed from this cool little tool.