Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 804
nicolaskruchten Avatar asked Jan 22 '11 15:01

nicolaskruchten


People also ask

Why should you use CoffeeScript instead of JavaScript?

CoffeeScript is something that makes even good JavaScript code better. CoffeeScript compiled code can do everything that natively written JavaScript code can, only the code produced by using CoffeeScript is way shorter, and much easier to read.

Is CoffeeScript same as JavaScript?

One crucial difference between the two languages is that TypeScript is the superset of JavaScript while CoffeeScript is a language which is an enhanced version of JavaScript. Not just these two languages but there are other languages such as Dart, Kotlin, etc. which can be compiled into JavaScript.


2 Answers

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');
like image 193
matyr Avatar answered Sep 21 '22 18:09

matyr


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.

like image 31
Olivier Lalonde Avatar answered Sep 21 '22 18:09

Olivier Lalonde