Closure-Compiler and Ant to compress JavaScript cover image

Closure-Compiler and Ant to compress JavaScript

Andrew Alba • April 5, 2012


Having used Eclipse and now IntelliJ for some time, I have often found it handy to build applications with Ant. It has been some time since I have taken a look at the process I was using and I really needed to find a better way to compress my JavaScript files, so I decided to look at refreshing the build.

My previous method had me setting up various properties, determining the OS being used and then targeting the compression of the JavaScript in the ant build.xml file. The process worked, but it was ugly and every OS had a different target for calling closure-compiler.

After several hours of reading the closure-compiler documentation, I happened to come across just what I was looking for (by accident). Closure-compiler now has a class for compiling in Ant []. What a find for me.

So here is how it works.

First you need to define the jscomp task-

<taskdef name="jscomp" classname=""

This creates a task named jscomp using compiler jar and class named CompileTask located in the Closure-Compiler directory.

Next we need to create our target. I simply named mine “compile”. Nested inside the target I call the jscomp task passing it the attributes. This is simple, but was tricky as some of the values passed to the attributes differ from the documented values.

For example, the compilation level will accept the following values “WHITESPACE_ONLY”,”SIMPLE_OPTIMIZATIONS”,”ADVANCED_OPTIMIZATIONS” via command line, but with the class the attribute values are “whitespace”,”simple”,”advanced”.

Finally nested inside of the jscomp task, we define our “externs” and “source” files. In my case I didn't really need to define any externs, but for a demonstration purposes, I have provided it the code.

<target name="compile">

    <jscomp compilationlevel="simple" warning="verbose" debug="false"

        <externs dir="${basedir}/closure-compiler/contrib/externs">
            <file name="jquery-1.7.js"/>

        <sources dir="${assetsPath}">
            <file name="myfile.js"/>



That should be all you need inside your ant build file to create your compressed/minified JavaScript code.