So are you ready to give CoffeeScript a try? In this article I will demonstrate how to install it, as well as its basic concepts.
You can install CoffeeScript globally using the Node Package Manager (npm) by typing the following command in to your terminal:
npm install coffee-script -g
You should install it globally so you can later access it in terminal with the command
If you need a primer on using npm, then please refer to this recently published SitePoint article.
CoffeeScript files have the
.coffee file extension. These files are either manually compiled, or you set a watcher that will compile your script each time it is saved with different contents.
To compile manually, go to the directory where the script is:
And run the following command:
coffee -c app.coffee
This will create an
app.js file in the same directory which you can then include in your project.
However, you most likely want
app.js to be refreshed each time you save the file. Therefore you compile it and add a watcher by typing:
coffee -cw app.coffee
Please note that in the latest version of CoffeeScript (1.9.1) there is a bug that causes the watcher not to work. All of the following examples were tested using CoffeeScript v 1.9.0.
; ) at the end of a line.
This means that you write:
hasBody = true
instead of :
var hasBody = true;
You can also call functions without using parentheses, but that is desirable only for outermost function calls. Therefore, you can do the following:
$(".messages") .show 'slow'
Indentation matters a lot in CoffeeScript. You should indent with two spaces or a tab:
if hasBody alert "Hello Body" else alert "No Body"