require()'ing a CoffeeScript file from a JavaScript file or REPL


I'm using Node.js and wanting to incorporate CoffeeScript into my workflow. I have two use-cases:

  1. I want to be able to write JavaScript files which require() CoffeeScript modules
  2. I want to be able to load CoffeeScript modules from within the node REPL

For case #1: I can just compile from .coffee to .js and require() the .js module, as a workaround.

For case #2: Right now I'm eval()ing the output of coffee-script.compile().

Is there a better, more unified way to do this?

1/2/2013 3:47:11 PM

Accepted Answer

The coffee-script module registers its extension once required.

$ echo 'console.log "works"' >

$ echo '
> require("coffee-script")
> require("./module")
> ' > test.js

$ node test.js

$ node
> require('coffee-script'); require('./module')

Edit: This behaviour has changed with the relase of CoffeeScript 1.7.0. Now you need to do:

2/10/2014 1:05:01 PM

A more versatile solution would be to use better-require.

npm install better-require

It lets you require() CoffeeScript files, no pre-compilation needed. (It also lets you require() a bunch of other file formats: CoffeeScript, clojurescript, yaml, xml, etc.)

In the case of CoffeeScript, it simply requires the coffee-script module.

var myModule = require('./');
var clojurescriptModule = require('./mymodule.cljs');
// etc.

Disclosure: I wrote better-require.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow