Running and Compiling CoffeeScript

Like most scripting languages, CoffeeScript has a REPL (“read-eval-print loop,” a term that originated with Lisp) where you can run commands interactively. To enter the REPL, just run coffee:

 $ ​​coffee
 coffee>​​ ​​audience​​ ​​=​​ ​​'world'
 'world'
 coffee>​​ ​​"Hello, #{audience}!"
 'Hello, world!'

To exit the REPL, press Ctrl-d.

The REPL handily shows you the output of each expression you enter. However, editing nontrivial amounts of code on the REPL is a pain. So how do we make coffee evaluate code written in our favorite text editor?

Create a file named hello.coffee with this code:

 rl = require(​'readline'​).createInterface
  input: process.stdin
  output: process.stdout
 
 rl.question ​"To whom am I speaking? "​, (audience) ->
  console.log(​"Hello, ​​#{​audience​}​​!"​)

Save the file and run it with coffee hello.coffee:

 $ ​​To​​ ​​whom​​ ​​am​​ ​​I​​ ​​speaking?​​ ​​Trevor
 Hello, Trevor!

Behind the scenes, this command compiles hello.coffee into JavaScript and runs the resulting code. Let’s try performing those steps separately so that we can look at the JavaScript output. Run the same command, but with the -c (“compile”) flag. You should now have a file named hello.js in the same directory. Try running it with node hello.js. (Notice how coffee imitates node’s command syntax whenever possible.)

The coffee command has many more tricks up its sleeve, but we won’t be using them in this book. Instead, we’ll use Grunt[22] in later chapters to do the heavy lifting of turning CoffeeScript source into production-ready JavaScript.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.128.105