Reputation: 474
Out of curiosity how does the coffee-script module handle require 'xxx'? It must be compiling the required file before node can load it... Does it have a specific handling for the 'require' function?
Thanks.
Upvotes: 1
Views: 196
Reputation: 231738
So if I have a coffee
file with the line
x = require './ls.coffee'
and run it directly with coffee, e.g. coffee foo.coffee
, ls.coffee
is loaded with the coffee extension (compiled and run).
But if I compile that script coffee -c foo.coffee
, and run it with node, node foo.js
, I get an error. Node no longer has the require
extension set, and all it sees is the Coffeescript code.
Upvotes: 0
Reputation: 187292
It looks like that's all handled right here:
https://github.com/jashkenas/coffee-script/blob/master/src/extensions.coffee
Which takes advantage of node's ability to register extensions that runs a callback when loaded. This is now deprecated, it seems, but the functionality is still present and working.
It does other stuff too, including some gnarly monkeypatching, but here's the most relevant snippet:
# Load and run a CoffeeScript file for Node, stripping any `BOM`s.
loadFile = (module, filename) ->
answer = CoffeeScript._compileFile filename, false
module._compile answer, filename
# If the installed version of Node supports `require.extensions`, register
# CoffeeScript as an extension.
if require.extensions
for ext in CoffeeScript.FILE_EXTENSIONS
require.extensions[ext] = loadFile
Upvotes: 1