coffee-script模块如何工作?

出于好奇,咖啡脚本模块如何处理需要'xxx'? 它必须在节点可以加载之前编译所需的文件…它是否具有“require”function的特定处理?

谢谢。

看起来这一切都在这里处理:

https://github.com/jashkenas/coffee-script/blob/master/src/extensions.coffee

它利用节点注册扩展的能力, 在加载时运行callback。 现在看来,这已经被弃用了,但function仍然存在并且正在工作。

它也做其他的东西,包括一些粗糙的monkeypatching,但这里是最相关的片段:

# 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 

所以,如果我有一个coffee文件的线

 x = require './ls.coffee' 

并用咖啡直接运行,例如coffee foo.coffeels.coffee加载咖啡扩展(编译和运行)。

但是,如果我编译脚本coffee -c foo.coffee ,并运行它与节点, node foo.js ,我得到一个错误。 节点不再具有require扩展集,它看到的只是Coffeescript代码。