Friday, December 16, 2011

Compressing Javascript and CSS using YUI and ANT

Before we look into more specifics you will have to download these two:
1. YUICompression jar from the Yahoo developer site: http://yuilibrary.com/download/yuicompressor/
2. YUIAnt jar file from http://www.ubik-ingenierie.com/miscellanous/YUIAnt/


Place the YUIAnt.jar and YUICompression jar into the lib directory of the project.


build.xml:



<property name="tools.lib.dir" value="tools"/>
<property name="jsmin.dir" value="jsmin"/>
<target name="cleanJSMin" description="Remove all generated files.">
    <delete dir="${jsmin.dir}"/>
</target>
<target name="minify" depends="cleanJSMin" description="Minifiy a set of files">
    <taskdef name="yuicompress" classname="com.yahoo.platform.yui.compressor.YUICompressTask">
        <classpath>
            <pathelement path="${tools.lib.dir}/yuicompressor-2.4.7.jar"/>
            <pathelement path="${tools.lib.dir}/YUIAnt.jar"/>
            <pathelement path="${tools.lib.dir}/rhino-1.6R7.jar"/>
        </classpath>
    </taskdef>
    <yuicompress linebreak="16000" warn="false" munge="no" preserveallsemicolons="true"
     outputfolder="${jsmin.dir}">
        <fileset dir="${basedir}/WebContent">
            <include name="js/jsp/*.js"/>
            <include name="js/princess/*.js"/>
            <include name="**/*.css"/>
        </fileset>
    </yuicompress>
</target>


                 
     


The reason why I prefer to minify the js and css files into a temporary directory is because we use Jenkins. If we minified the js and css files in the same location, when Jenkins update from SVN, the build will fail because of conflicts. So the solution is put the js and css into a temporary directory then copy them over to the war file.