Espresso ristretto with Meteor and CoffeeScript

In my mind CoffeeScript is to JavaScript as Espresso ristretto is to Coffee, and Meteor is our Moka!

Are you ready to convert the default Meteor application in CoffeeScript? Let's go coding.

Create a new Meteor application

Open your terminal and type meteor create espresso. We will not launch meteor, for the moment.

$ meteor create espresso
espresso: created.      

To run your new app:  
  cd espresso                                 
  meteor   

Cd into the espresso folder with cd espresso and list all the files with ls -al.

$ cd espresso && ls -al

espresso.css  
espresso.html  
espresso.js  
.meteor

Open espresso.js and look at the JavaScript code

if (Meteor.isClient) {  
  // counter starts at 0
  Session.setDefault("counter", 0);

  Template.hello.helpers({
    counter: function () {
      return Session.get("counter");
    }
  });

  Template.hello.events({
    'click button': function () {
      // increment the counter when button is clicked
      Session.set("counter", Session.get("counter") + 1);
    }
  });
}

if (Meteor.isServer) {  
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

The CoffeeScript package is maintained by the Meteor Development Group (aka MDG), we don't need to add the author in the command line, like for the packages maintained by the community: meteor add author:packageName

~/espresso$ meteor add coffeescript

Now the coffeescript package is installed, the last two things to do are

  • Rename espresso.js in espresso.coffee
  • Replace the JavaScript code with CoffeScript code inside espresso.coffee

Rename espresso.js in espresso.coffee

~/espresso$ mv espresso.js espresso.coffee

Replace the JavaScript code with the following CoffeScript code

if Meteor.isClient  
  Session.setDefault "counter", 0

  Template.hello.helpers
    counter: -> Session.get "counter"

  Template.hello.events
    'click .button-inc': -> Session.set "counter", Session.get("counter") + 1
    'click .button-reset': -> Session.set "counter", 0

if Meteor.isServer  
  Meteor.startup ->

Our little cup of espresso ristretto is ready.

In the espresso.js file we have typed 444 characters, in our espresso.coffee 314, ( 444 - 314 ) = 130 characters less.
Not bad, for sure your fingers will thank you.

Explanation

In CoffeeScript we don't need to use curly braces, semicolon, parenthesys; for statements definition we use indentation, so: less characters = less code = less lines of code.

http://coffeescript.org

Start meteor

Now start meteor, and take a look at http://localhost:3000.
Nothing has changed, the app works as expected, and this is exactly what we want. :)

Conclusion

We have only to write CoffeeScript code and hit save in our editor. Meteor, behind the scenes, compiles the CoffeeScript code into the equivalent JavaScript.

In conclusion, if you like coding (or want to code) Meteor applications in CoffeeScript, Meteor has you covered.