Saturday, March 28, 2009

Ant Task for YUICompressor

Here is a macro I wrote to look for javascript files recursively in a source folder, compress every one of them using YUICompressor and copy the compressed javascript files to target folder. The usage of the task cannot get any simpler than this:-


< target name="compress" >
<yuicompress src="uncompressed_folder" target="target_folder"/>
</target>

Here is the macro definition for yuicompress. Just place it before the yuicompress task in buildfile.xml


<property description="YUICompressor" name="YUICompressor" value="./build/yuicompressor/yuicompressor-2.4.2.jar" />


<macrodef name="yuicompress">
<attribute name="src"/>
<attribute name="target"/>
<sequential>
<echo message="Compressing files at @{src}" />
<!-- create target folder if it doesn't exist already -->
<mkdir dir="@{target}"/>
<!-- Create directories recursively first.
Exclude javascript files as they will be put by YUICompressor later on -->

<copy todir="@{target}">
<fileset dir="@{src}">
<exclude name="**/*.js"/>
</fileset>
</copy>

<!-- Compress js files recursively -->
<apply executable="java" parallel="false" verbose="true" dest="@{target}">
<fileset dir="@{src}">
<include name="**/*.js"/>
</fileset>
<arg line="-jar" />
<arg path="${YUICompressor}" />
<arg value="--charset" />
<arg value="ANSI" />
<arg value="-o" />
<targetfile />
<mapper type="glob" from="*.js" to="*.js" />
</apply>
<echo message="Files compressed and copied to @{target}" />
</sequential>
</macrodef>


Reminder: Remember to replace YUICompressor's location marked in red above

Please leave a comment if you found it useful.