【问题标题】:Requiring CoffeeScript file from within another CoffeeScript file with nodejs使用 nodejs 从另一个 CoffeeScript 文件中需要 CoffeeScript 文件
【发布时间】:2014-04-18 02:31:29
【问题描述】:

我想知道您是否能够从另一个咖啡脚本中要求一个咖啡脚本。

我的示例代码来自文件“user.coffee”

class UserObj
    constructor: (@name) ->
        console.log @name

我在主文件中的示例代码

require "./user.coffee"

User = new UserObj "Example"

这可能来自一个coffeescript文件还是一个js文件?

【问题讨论】:

标签: node.js coffeescript


【解决方案1】:

是的,这是可能的。

user.coffee:

exports.UserObj = 
class UserObj
    constructor: (@name) ->
        console.log @name

main.coffee:

{UserObj} = require "./user"

User = new UserObj "Example"

【讨论】:

  • 但这仅适用于 Node 对吧?我认为 CoffeeScript 可能已经将编译 main.js 所需的文件放在一起
  • @ThomasWelton 这仅适用于 Node。目前 CoffeeScript 编译器只是一个文件到文件的转编译器,它不做任何项目结构分析,因此没有聚合。可能有other tools 处理该问题。我什至记得writing one myself
  • 谢谢。后来我继续使用 requirejs 来加载咖啡脚本模块和类,我对此非常满意。
  • 如果您对每个文件使用一个类,那么我更喜欢module.exports = UserObj,现在原型已暴露在文件之外,并且{UserObj} = require './user' 不是必需的。构造函数的加载只是:UserObj = require './user'
【解决方案2】:

您可以使用此库coffee-stir 来包含其他依赖项。它是一种仅使用 web required 的方法,它会在您使用它时添加依赖项。 仅供参考,当我遇到类似问题时,我制作了 lib

【讨论】:

    猜你喜欢
    • 2014-06-15
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2016-09-02
    相关资源
    最近更新 更多