【问题标题】:How does the coffee-script module work?咖啡脚本模块是如何工作的?
【发布时间】:2013-11-04 09:29:12
【问题描述】:

出于好奇,coffee-script 模块如何处理 require 'xxx'? 它必须在节点加载它之前编译所需的文件......它是否对'require'函数有特定的处理?

谢谢。

【问题讨论】:

    标签: node.js coffeescript


    【解决方案1】:

    看来这一切都在这里处理好了:

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

    这利用了节点register extensions that runs a callback when loaded. 的能力,现在看来,这已被弃用,但该功能仍然存在并且可以工作。

    它也做其他事情,包括一些粗糙的猴子补丁,但这是最相关的 sn-p:

    # 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
    

    【讨论】:

    • 但值得注意的是,此功能在 Node.js 中已被弃用。详情见:nodejs.org/api/globals.html#globals_require_extensions
    • 那么loadFile 函数是如何使用的呢?它不会更改yyy = require xxx 行的翻译。它的改变足以使其成为 node.js 可以使用的有效 Javascript。通常xxx 是 Javascript,无论是从头开始编写还是从 Coffeescript 编译。
    • @hpaulj 该回调在节点需要特定扩展名的文件时运行。它这样做:answer = CoffeeScript._compileFile filename, false 将返回 javascript。节点可以执行它。
    【解决方案2】:

    所以如果我有一个coffee 文件,其中包含该行

    x = require './ls.coffee'
    

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

    但是,如果我编译该脚本 coffee -c foo.coffee,并使用节点运行它,node foo.js,我会收到错误消息。 Node 不再有 require 扩展集,它看到的只是 Coffeescript 代码。

    【讨论】:

      猜你喜欢
      • 2018-01-25
      • 2012-10-12
      • 2023-03-08
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多