Monday, January 28, 2013

CoffeeScript in Node.js

I'm throwing together a Node.js and Express application at the moment and trying out in anger a few of the technologies I've read about but not practiced. One of those of CoffeeScript.

The CoffeeScript compiler is primarily available implemented on Node.js as a command line utility. You might expect that for Node.js projects, there should be a way where compilation could be handled transparently without intermediate Javascript files during development.

And you would be right. But how it works is not well documented, and so I wanted to make a note of that here. I found the information in a blog post by Max Aller.

Here is the summary for an application-homed install:
  1. Include coffee-script in your application package.json dependencies:
      "dependencies": {
        "express": "3.0.6",
        "jade": "*",
        "coffee-script": "*"
  2. Install dependences ( npm install in the application folder)
  3. Import the module: require('coffee-script'); in your application
Once done, the .coffee extension is transparently compiled to Javascript in any require() statement.

For example:

# will find, parse and execute ./


  1. As an experiment, I tried converting bootstrap.js and publish.js (in server/) to coffeescript, but Meteor was unhappy.

    It seems that coffeescript doesn't allow global variables -- you either get 'this.var' or locals.

    The suggestion of using "window"-relative for globals doesn't work when there is no window -- (e.g., on the server).

    Have you figured out how to use coffeescript global variables in server code?

  2. Hi Alan, this hasn't really come up for me, but I found a this stackoverflow thread that has an amazingly indepth answer. Hopefully it will be helpful.