node.js - 创建单 Node 模块以访问用 CoffeeScript 编写的单独文件中的多个扩展类

标签 node.js inheritance module coffeescript npm

我想创建一个包含多个类的单个 Node 库,每个类都使用不同文件中的 CoffeeScript 编写并相互扩展。例如,假设我在 node_modules/mymodule/src 中有以下文件:

文件 1:

  class Base
    constructor: (@foo) ->

  module.exports = Base

文件 2:

  Base = require './Base.coffee'

  class Derived extends Base
    constructor: (@bar) ->
      super

  module.exports = Derived

文件 3:

  Base = require './Base.coffee'

  class Derived2 extends Base
    constructor: (@baz) ->
      super

  module.exports = Derived2

有什么方法可以以这种方式绑定(bind)这 3 个类,以便我可以在 package.json 文件中定义“mymodule”,然后像这样访问模块及其类?

使用 mymodule 文件:

  my module = require 'mymodule'

  Base = new mymodule.Base
  Derived = new my module.Derived
  Derived2 = new my module.Derived2
  #Do stuff

我不知道在 package.json 中该怎么做才能实现这一点,而且我在任何地方都找不到这方面的文档。这可能吗?

最佳答案

您可以使用main配置模块的入口点并在那里公开您的类。 (我还没有使用 CoffeeScript 完成此操作)。

The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module's exports object will be returned.

This should be a module ID relative to the root of your package folder.

将您的 main 配置为指向 index.js 或类似内容。然后你的index.js看起来像这样:

module.exports.Base     = require('./pathtobase/Base.coffee');
module.exports.Derived  = require('./pathtobase/Derived.coffee');
module.exports.Derived2 = require('./pathtobase/Derived2.coffee');

关于node.js - 创建单 Node 模块以访问用 CoffeeScript 编写的单独文件中的多个扩展类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18970206/

相关文章:

asp.net-mvc - MVC 发布复杂对象列表

python - 如何在每次更改后无需重新启动解释器的情况下开发 Python 模块/包?

python - 从目录导入python中的用户定义模块

javascript - MarkLogic 8 Ingestion Job 在 JavaScript 中对集合进行非规范化

node.js - nginx通过docker主机映射路由,对于每个路由,调用不同的容器

node.js - 在 Node.js 中使用私钥和 "SHA256 with RSA"算法生成签名

c# - 继承初始化字段

javascript - 如果 req.param === 未定义,如何更改 req.param

带有派生类的 base_class 上的 C++ 继承和虚拟关键字

powershell - 尝试导入模块时故意使模块失败