54

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?

3
  • What about the CoffeeScript REPL, coffee? Commented Jan 22, 2011 at 15:53
  • That REPL is very primitive compared to the node one: it lacks colour, autocompletion, multi-line statements etc Commented Jan 22, 2011 at 19:06
  • 5
    Update: the coffee REPL is now awesome :) Commented Sep 11, 2011 at 2:31

2 Answers 2

95

The coffee-script module registers its extension once required.

$ echo 'console.log "works"' > module.coffee

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

$ node test.js
works

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

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

require('coffee-script/register');
Sign up to request clarification or add additional context in comments.

3 Comments

Huh, why didn't I think of that? :)
require.extensions is now deprecated and there is no alternative yet.
I expect it to stick around as it's a stable feature and, as you mentioned, there are not alternatives yet.
12

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.

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

Disclosure: I wrote better-require.

2 Comments

the central problem with require.extensions—that registering an extension changes global state, for your entire application—is, sadly, not addressed by better-require, meaning that things will break if any of your 3rd party sub-modules happen to depend upon a different version of, say, Yaml, or CoffeeScript.
better-require also doesn't load ".litcoffee" modules by default, whereas they can be loaded via require('coffee-script/register');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.