22 December 2010

Using YUI Compressor.NET in Visual Studio 2010 to compress CSS and JavaScript

Compressing css and js files make website to load faster. There are many compress tools out there to do this. But it is difficult to compress manually every time you build ur visual studio project.

I found YUI compressor.net at CodePlex and add the compression batch process to project post build event and volla! No more manual compress headache anymore.

Here is the steps I do (bare minimal):

Download the dll from yuicompressor.codeplex.com

1. Create the Library folder in your project
2. Copy Yahoo.Yui.Compressor.dll and EcmaScript.NET.modified.dll to the folder

3. Create MSBuild folder
4. Copy sample MSBuild.xml from yuicompressor.codeplex.com/wikipage?title=Sample%20MSBuild.xml%20File&ProjectName=yuicompressor

5. Now, Right click on website > Property > Build Events >
6. Add $(MSBuildBinPath)\msbuild.exe "$(ProjectDir)MSBuild\MSBuild.xml" /p:SourceLocation=$(ProjectDir)

7. Open MSBuild.xml
8. Change UsingTask AssemblyFile correctly pointed to copied Yahoo.Yui.Compressor.dll.

9. Set CssOutputFile for conbined and compressed css file
10. Set JavaScriptOutputFile for conbined and compressed js file

11. Add css and js files to compress in ItemGroup

e.g
<CssFiles Include="$(SourceLocation)Styles\common.css"/>
<CssFiles Include="$(SourceLocation)Styles\common1.css"/>

<JavaScriptFiles Include="$(SourceLocation)Scripts\common.js"/>
<JavaScriptFiles Include="$(SourceLocation)Scripts\common1.js"/>

if you don't want to compress your js or css files into single file, you can use multiple CompressorTask

For more info you can check the instruction video here :

Enjoy

No comments: