Back to Coffeescript

Nodejs Usage

documentation/sections/nodejs_usage.md

2.7.01.6 KB
Original Source

Node.js

If you’d like to use Node.js’ CommonJS to require CoffeeScript files, e.g. require './app.coffee', you must first “register” CoffeeScript as an extension:

coffee
require 'coffeescript/register'

App = require './app' # The .coffee extension is optional

If you want to use the compiler’s API, for example to make an app that compiles strings of CoffeeScript on the fly, you can require the full module:

coffee
CoffeeScript = require 'coffeescript'

eval CoffeeScript.compile 'console.log "Mmmmm, I could really go for some #{Math.pi}"'

The compile method has the signature compile(code, options) where code is a string of CoffeeScript code, and the optional options is an object with some or all of the following properties:

  • options.sourceMap, boolean: if true, a source map will be generated; and instead of returning a string, compile will return an object of the form {js, v3SourceMap, sourceMap}.
  • options.inlineMap, boolean: if true, output the source map as a base64-encoded string in a comment at the bottom.
  • options.filename, string: the filename to use for the source map. It can include a path (relative or absolute).
  • options.bare, boolean: if true, output without the top-level function safety wrapper.
  • options.header, boolean: if true, output the Generated by CoffeeScript header.
  • options.transpile, object: if set, this must be an object with the options to pass to Babel. See Transpilation.
  • options.ast, boolean: if true, return an abstract syntax tree of the input CoffeeScript source code.