By compressing javascript files page loading time is significantly reduced.

Below I've wrote an ant task that can be used in a build file of a project to 

compress javascript source files. 

Before using it, be sure you have

custom_rhino.jar and ant-contrib.jar added to your classpath.

<target name="js-compress">

		<property name="input.dir" value=""/>

		<property name="output.dir" value=""/>

		<echo message="compress files from ${input.dir}" />

		<for param="file">

			<path>

				<fileset dir="${input.dir}" includes="**/*.js">

					<depth max="2"/>

				</fileset>

			</path>

			<sequential>

				<echo message="file: @{file}"/>

				<antcall target="js-file-compress">

					<param name="input" value="@{file}"/>

					<param name="output" value="@{file}"/>

				</antcall>

			</sequential>

		</for>

	</target>

	

	<target name="js-file-compress" description="compress js files">

		<property name="input" value=""/>

		<property name="output" value=""/>

		<java jar="lib/rhino/custom_rhino.jar" fork="true">

			<arg value="-c"/>

			<arg file="${input}"/>

			<redirector output="${output}"/>

		</java>

	</target>

Ant task  can be used as follows  

Supposing js deploy directory is in web/js:
	<antcall target="js-compress">
			<param name="input.dir" value="web/js"/>

			<param name="output.dir" value="web/js"/>

	</antcall>

4 responses to “Ant task for JavaScript compression

  1. Do note this is actually an ant target, not ant task (ala .
    I actually prefer this way, as it wouldn’t necessitate an additional jar for ant (besides those listed).

  2. Excellent! I was looking for something like this. There’s just one minor problem. While you can specify separate input and output directories, it only uses one and overwrites your originals. This is because the antcall to js-file-compress passes the same @{file} to both the input and output parameters. Replacing @{file} with ${output.dir} on the output parameter doesn’t help either because rhino expects a filename for output and not a directory.

    I am using it for single directory at the moment by copying all my files then compressing them.

Leave a Comment:

Your email address will not be published. Required fields are marked *