Even if you don’t decide to adopt
CoffeeScript in your own programs,
it’s worth playing with the language
to get the hang of things.
Starting Off
I’m going to assume you already have
installed CoffeeScript, as well as any
support files, such as a mode for your
editor. Create a bare-bones HTML file,
as shown in Listing 1, and a stylesheet
(coffeescript.css), in the same directory,
similar to what’s shown in Listing 2.
Notice how in the HTML file, I include
two JavaScript files:
<script src=" http://ajax.googleapis.com/ajax/libs/ ;jquery/1.4.2/jquery.min.js"></script> <script src="app.js"></script>
The first probably is recognizable as
the Google-hosted version of a minified
version of jQuery. But the second file,
app.js, is the target of the CoffeeScript
compilation—that is, you’re not going
to write app.js directly. Rather, you’re
going to write CoffeeScript that compiles
into JavaScript.
You do this by creating (in the same
directory as the HTML file, unless
you want to change the paths in the
<script> tag) a CoffeeScript program,
named app.coffee. Just to test things,
I created a very simple CoffeeScript
AT THE FORGE
COLUMNS
Listing 1. coffeescript.html
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type"
;content="text/html; charset=utf- 8" /> <link rel="stylesheet" type="text/css"
;href="coffeescript.css" /> <title>CoffeeScript</title> <script src=" http://ajax.googleapis.com/
;ajax/libs/jquery/1.4.2/
;jquery.min.js"></script> <script src="app.js"></script>
</head> <body> <h1>Headline</h1> <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> </body> </html>
program that uses the standard (and
annoying!) alert dialog to say “hello”:
alert "hello"
Save this file as app.coffee. On the
command line, you then want to tell
CoffeeScript to compile app.coffee into
app.js. (Otherwise, it’ll try to execute
your program, which not only will mean
that the resulting JavaScript isn’t available
WWW.LINUXJOURNAL.COM SEPTEMBER 2011 | 33