Saturday, February 9, 2008

Modifying HTML/JSP Files with Ant

After compressing and concatenating your javascript files with YUI Compressor like I showed last week, you will probably want to have your build process modify your html/jsp files to point to them. To do this you can use an Ant task called replaceregexp.

Here is an example:

1. First modify your html so that it looks something like this:
<script type="text/javascript" src="scripts/MyFile1.js"></script>
<script type="text/javascript" src="scripts/MyFile2.js"></script>
<script type="text/javascript" src="scripts/MyFile3.js"></script>

Notice the @@myjs block. Everything between those comments (inclusive) will be replaced in the next step.

2. Add the following into your Ant build script:

<target name="set-js-includes" depends="init">
<fileset dir="../build/WebContent" includes="**/*.html, **/*.jsp">
<regexp pattern="&lt;!--@@myjs.start-->[-a-zA-Z0-9&lt;>\s'&quot;/=.!_]*&lt;!--@@myjs.end-->"/>
<substitution expression="&lt;script type=&quot;text/javascript&quot; src=&quot;scripts/MyFile.js&quot;>&lt;/script>"/>

You will need to make sure that the paths are pointing to the correct place.

Now you should have something that looks like this:

<script type="text/javascript" src="scripts/MyFile.js"></script>

After doing all of this there is an important question that must be asked: Why? Well, now you can have all of you javascript code neatly separated into different files during development, but built into one file that is faster to download for production. Just remember to test the output of this procedure as it will modify your code.

Have a good one.

Sunday, February 3, 2008

Building Javascript with Ant and YUI Compressor

I recently spent some time wrestling with Ant and YUI Compressor.
What I wanted to do was take a group of js files and run them through the compressor, and then append them into a single file in a specific order.

Here is what I did:

<apply executable="java" parallel="false">
<filelist dir="WebContent/scripts">
<file name="myFile1.js" />
<file name="myFile2.js.js" />
<file name="dir1/dir2/myFile3.js" />

<arg line="-jar"/>
<arg path="${yuicompressor.jar.file}"/>
<redirector output="../build/WebContent/scripts/main.js" append="true">

I hope this helps.