Compressing CSS and JavaScipt with MSBuild
Want to compress your CSS and Javascript files during your build process? Here is what you need.
Download CSSTidy, and add the executable somewhere on your build machine.
Download and install the MSBuild Community Tasks, or you can do just the Jazmin JSCompress task, though I didn’t do that so I don’t have any source XML for that.
To be clean, I added a Property for the location of CssTidy
<PropertyGroup>
<CssTidy>c:\BuildTools\CssTidy.exe</CssTidy>
</PropertyGroup>
Also I registered the MSBuildCommunityTasks
<!-- Required Import to use MSBuild Community Tasks -->
<Import Project=”$(MSBuildExtensionsPath)\MSBuildCommunityTasks\
MSBuild.Community.Tasks.Targets”/>
Then, build a list of all the files you want to compress.
<ItemGroup>
<CssFiles Include=”$(websitedir)\**\*.css”/>
<ScriptFiles Include=”$(websitedir)\**\*.js”/>
</ItemGroup>
$(websitedir) is just a variable for where the website is, obviously I could have used c:\inetpub\wwwroot or whatever instead.
Then I build two tasks, one that calls CssTidy…
<Target Name="compress_css">
<Attrib Files=”%(CssFiles.FullPath)” ReadOnly=”false”/>
<Exec Command=”$(CssTidy) %(CssFiles.FullPath) %(CssFiles.FullPath) –template=highest” />
</Target>
If your not familiar with the %() syntax, this causes MsBuild to iterate over each item in the CssFiles collection and run this tag for each instance. Otherwise I would get a semi-colon delimited list which nothing handles that well.
The Attrib tag makes everything write-able thus the ReadOnly=”false” attribute, this didn’t seem to be an issue for CssTidy, but it was for JSCompress and I put it here just incase it becomes an issue one day.
The Exec Line executes the CssTidy program, with the FullPath of the searched file (this is meta-data of the item), its included twice to represent the input and output. The –template=highest portion just says do your absolute best!
Then the you add one for JSCompress…
<Target Name="compress_js">
<Attrib Files=”%(ScriptFiles.FullPath)” ReadOnly=”false”/>
<JSCompress Files=”%(ScriptFiles.FullPath)”></JSCompress>
</Target>
Attrib we’ve been over, this is really important here, as JSCompress was failing on readOnly files.
Then I tell it to run the JSCompress tag for each of the ScriptFiles. I feel like I’m explaining exactly what your seeing and already understanding. I hate it when people do that.
Then you need to call these targets.
<CallTarget Targets="compress_css"/>
<CallTarget Targets=”compress_js”/>
Not much to it. Hopefully this helps you bring quick loading times to all the web surfers of the world.
Thanks from this link:
http://blackbeltcoder.net/2007/04/20/javascript-and-css-compression-in-msbuild/
