Compressing CSS with YUI Compressor for .Net
The best solution is to minimize JS files while building release version and in this atricle I’ll show you how to use YUICompressor.NET in MSBuild task and run it as build event in your project.
Step 1. Get a YUICompressor.NET
It’s very easy: just go to YUICompressor .NET codeplex page and get most recent version.
Step 2. Write MSBuild task
It is also a very common task: all you have to do is to use build task called CompressorTask from YUICompressor.NET assembly^
<?xml version="1.0" encoding="utf-8" ?> <Project xmlns="http://schemas.microsoft.com/developer/MsBuild/2003"> <UsingTask TaskName="CompressorTask" AssemblyFile="..packagesYUICompressor.NET.188.8.131.52libNET35Yahoo.Yui.Compressor.dll" />
Then we need to tell MSBuild to run our task on js files, that need to be minified:
And let’s not forget to run minification task only on Release configuration:
<Target Name="CareToCare_JS_CSS_Minification" Condition="'$(Configuration)'=='Release'"> <ItemGroup> <CssFiles Include="$(MSBuildProjectDirectory)PublicStyles*.css" /> <CssFiles Include="$(MSBuildProjectDirectory)PublicStylesthemesbase*.css" /> </ItemGroup>
The last thing left: run CompressorTask with required arguments.
See Codeplex docs for details about these settings.
<CompressorTask CssFiles="@(CssFiles)" DeleteCssFiles="false" CssOutputFile="$(MSBuildProjectDirectory)PublicStylesstyles.min.css" CssCompressionType="YuiStockCompression" PreserveAllSemicolons="False" DisableOptimizations="Nope" EncodingType="Default" LineBreakPosition="-1" LoggingType="ALittleBit" ThreadCulture="en-au" IsEvalIgnored="false" /> </Target> </Project>
Okay, now we have our task. Save it as .xml file (for example BuildConfig.xml) and let’s attach this task to our project, so MSBuild will run it while building project.
FYI: VisualStudio also uses MSBuild to build projects and solution. So, out solution will work with VisualStudio and plain MSBuild (on integration server, for example) as well.
To ass task to project, go to your project settings (Right click ->Proterties), pick Build Events section and paste following to “Post-build event command line”:
$(MSBuildBinPath)msbuild.exe /p:Configuration=$(ConfigurationName) "$(ProjectDir)BuildConfig.xml"
That’s it! Now when you’ll build your project with Release configuration, your .js files will be minified.