Tuesday, November 22, 2011

Getting Started with CoffeeScript


Getting Started with CoffeeScript


Note: You may also be interested in “CoffeeScript with WebSQL and jQuery“, which gives more examples of CoffeeScript code.
Lately in web development circles there has been a movement to make Javascript easier for everyone. Well, easier is probably the wrong word.  Lets just say that they want to “modernize” it’s syntax.  A little language has been gaining a lot of attention lately that does just this, and it’s called CoffeeScript.  A quick example of assigned on a condition:
big = true
number = 100 if big
Instead of:
var big = true;
if(big) {
   number = 100;
}
Anyways, this tutorial is about getting the CoffeeScript compiler up and running. To do this, you’re going to need Node.js and the Node Package Manager(NPM).

Step 1: Node.js

Getting Node to install is pretty straight forward. All you need to do is download the latest stable version from here and then run:
./configure
make
make install (may need to run as super user)

Step 2: Node Package Manager

Node Package Manager is the equivalent of EasyInstall for Python. It allows a user to install pre-made programs, like CoffeeScript, easily without worrying about build dependencies or any annoying stuff like that.
If you have Curl installed (most Linux/Mac users will), the easiest way to make this happen is to do the following:
curl http://npmjs.org/install.sh | sh
I personally ran into problems with this because of some permissions errors. If you run into this, check https://github.com/isaacs/npm/blob/master/README.md out which has extensive documentation on how to get around it.

Step 3: Install Coffee

Now that we have all of Coffee’s dependencies solved, you can install CofeeScript by doing:
npm install coffee-script

Step 4: Brew Some Cofee

Let’s make a math object…
math =
 cube: (x) -> x * x * x
 square: (x) -> x * x
 
startNumber = 2
cubeStartNumber = math.cube(startNumber)
squareStartNumber = math.square(startNumber)
alert "Cube: " + cubeStartNumber
alert "Square: " + squareStartNumber
Now, save this file to test.cs and then run coffee -c test.cs on the file. You will get a new file called test.js that looks like:
(function() {
  var cubeStartNumber, math, squareStartNumber, startNumber;
  math = {
    cube: function(x) {
      return x * x * x;
    },
    square: function(x) {
      return x * x;
    }
  };
  startNumber = 2;
  cubeStartNumber = math.cube(startNumber);
  squareStartNumber = math.square(startNumber);
  alert("Cube: " + cubeStartNumber);
  alert("Square: " + squareStartNumber);
}).call(this);

That’s it!

If you run in to any problems during the install process, drop a line in the comments and I’d be happy to help.

0 comments: