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/

相关文章:

java - 为什么我不能使用已实现接口(interface)的静态方法?

java - 类继承 : generic extends generic

javascript - 将对象保存在模块中并从不同的模块访问它

php - CodeIgniter 的 Mahana 模块

node.js - 应考虑使用 Node js 可伸缩性和性能将文件上传到 s3 的良好做法

javascript - Node.js 监听端口 9999 时发出运行时错误

node.js - 如何(正确)在 Node 中链接多个连续的 MSSQL 查询

c++ - 在 C++11 中对派生类使用基类运算符

Javascript - 正则表达式 - 全局搜索问题

perl - 如何安装一组特定版本的 Perl 模块?