Initial Setup

One of the easiest ways to initially play around with the library is to use it right inside the browser. Navigate to http://coffeescript.org and click on the Try CoffeeScript tab. The site uses a browser version of the CoffeeScript compiler, converting any CoffeeScript typed inside the left panel to JavaScript in the right panel.

You can also convert JavaScript back to CoffeeScript using the js2coffee project, especially useful when migrating JavaScript projects to CoffeeScript.

In fact, you can use the browser-based CoffeeScript compiler yourself, by including this script in a page, marking up any CoffeeScript script tags with the correct type:

<script src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js" type="text/javascript" charset="utf-8"></script>
<script type="text/coffeescript">
  # Some CoffeeScript
</script>

Obviously, in production, you don’t want to be interpreting CoffeeScript at runtime, as it’ll slow things up for your clients. Instead, CoffeeScript offers a Node.js compiler to pre-process CoffeeScript files.

To install it, first make sure you have a working copy of the latest stable version of Node.js and npm (the Node Package Manager). You can then install CoffeeScript with npm:

npm install -g coffee-script

The -g flag is important, as it tells npm to install the coffee-script package globally, rather than locally. Without it, you won’t get the coffee executable.

If you execute the coffee executable without any command line options, it’ll give you the CoffeeScript console, which you can use to quickly execute CoffeeScript statements. To pre-process files, pass the --compile option:

coffee --compile my-script.coffee

If --output is not specified, CoffeeScript will write to a JavaScript file with the same name, in this case my-script.js. This will overwrite any existing files, so be careful you’re not overwriting any JavaScript files unintentionally. For a full list of the command line options available, pass --help.

You can also pass the --compile option a directory, and CoffeeScript will recursively compile every file with a .coffee extension:

coffee --output lib --compile src

If all this compilation seems like a bit of an inconvenience and bother, that’s because it is. We’ll be getting onto ways to solve this by automatically compiling CoffeeScript files, but first let’s take a look at the language’s syntax.

Get The Little Book on CoffeeScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.