CoffeeScript is a neat language that is transcompiled into JavaScript but is more predictable and allows to write the same code with 1/3 fewer lines and of course with a (imho) nicer syntax.

CoffeeScript is nice but a vivid integration into our application build lifecycle with Maven is better and that is what the following example is all about.

Maven Dependencies

Though there are some alternatives, we’re using brew here so please add the following dependency to your Maven project:

<build>
    <plugins>
        <plugin>
            <groupId>com.voltvoodoo</groupId>
            <artifactId>brew</artifactId>
            <version>0.2.10</version>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

CoffeeScript Example

Now we need a simple CoffeeScript script to be compiled into JavaScript.

The following class simulates a simple countdown – if you’re new to CoffeeScript please take a look at the nice project website – there’s also an emulator to toy around ..

We’re creating a file named countdown.coffee in the directory src/main/coffeescript

class Countdown
 constructor:(@treshold) ->

 countDown: ->
 alert("beginning countdown from  #{@treshold}")
 for num in [@treshold..1]
 do (num) ->
 alert(num)
 alert("FIRE!!!!")

countdown = new Countdown 10
countdown.countDown()

That’s what the stuff looks like when running it on the emulator on coffeescript.org

coffeescript emulator 1 1024x793
Figure 1. Using the online CoffeeScript emulator
countdown 1024x792
Figure 2. Running the countdown

Compiling and the Result

Now let the compiler do his work and run

mvn package

And that’s what the compiled JavaScript countdown-class looks like – CoffeeScript looks nicer don’t you agree? :)

(function () {
 var Countdown, countdown;
 Countdown = (function () {
 function Countdown(treshold) {
 this.treshold = treshold;
 }
 Countdown.prototype.countDown = function () {
 var num, _fn, _ref;
 alert("beginning countdown from  " + this.treshold);
 _fn = function (num) {
 return alert(num);
 };
 for (num = _ref = this.treshold; _ref <= 1 ? num <= 1 : num >= 1; _ref <= 1 ? num++ : num--) {
 _fn(num);
 }
 return alert("FIRE!!!!");
 };
 return Countdown;
 })();
 countdown = new Countdown(10);
 countdown.countDown();
}).call(this);

Alternatives

There are a few alternatives out there – I don’t know which one is the best but I am open for any suggestion..

Tutorial Sources

I have put the source from this tutorial on myhttps://github.com/hascode/coffeescript-maven-tutorial[GitHub repository] – download ithttps://github.com/hascode/coffeescript-maven-tutorial/downloads[there] or check it out using Mercurial:

git clone https://github.com/hascode/coffeescript-maven-tutorial.git