Monday, October 19, 2009

Using Microsoft Ajax Minifier with Deployment Projects

It's been a while since I did a post here but this is worth it. Yesterday Microsoft's Scott Guthrie announced the new Microsoft Ajax Library (Preview 6) and the Microsoft Ajax Minifier. While I haven't checked out the new Ajax library I have had a bit of a play with the minifier.

Seeing as I was on the look out for a Javascript minifier for my current project this came at quite an opportune time. I found Stephen Walther's immensely helpful blog post about setting the Ajax Minifier to run automatically each time you build your project (you should go read that now before continuing here). The only problem with Stephen's sample is my current ASP.NET solution is set up in such a way as my website is a Website, not a Web Application so I don't have a .csproj file to edit.

Fear not! For I have found that I can simply transpose Stephen's sample code over to my deployment project's .csproj file with similar results. The following is the required markup from my deployment project's csproj file to generate minified scripts on the fly after deploying my website. I placed this at the very end of the markup, just before the closing </Project> tag.

CODE:


<PropertyGroup>
<BuildDependsOn>
$(BuildDependsOn);
MinifyJs
</BuildDependsOn>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\MicrosoftAjax\ajaxmin.tasks" />
<Target Name="MinifyJs">
<ItemGroup>
<JS Include="$(OutputPath)\js\*.js" Exclude="$(OutputPath)\js\*.min.js" />
</ItemGroup><AjaxMin SourceFiles="@(JS)" SourceExtensionPattern="\.js$" TargetExtension=".min.js" />
</Target>


Should look something like this:


The big difference here is the min.js files are generated on the fly in the DEPLOYED website (that'd be the $(OutputPath) location. Also, but not as important, my javascript files are in a folder called "js" unlike Stephen's which sit in the root of the site.

So there you go, minified Javascript files in your target site.