我想创建一个包含多个类的单个 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/