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.

Blueprint

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.

Add Reference - Visual Studio

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.

Minify tool

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.

Download a copy of the project here.

Some further reading:
http://www.olegsych.com/2008/09/t4-tutorial-creatating-your-first-code-generator/

http://blogs.msdn.com/webdevtools/archive/2009/01/29/t4-templates-a-quick-start-guide-for-asp-net-mvc-developers.aspx

Scott Hanselmans blog