在nodejs / commonjs中用coffeescript(zappa)重新导出模块(mongoose)

我正在使用mongoose @ 2.0.4,并且想到了将模块中的mongoose.connect()调用整齐地抽象出来。

所以使用nodejs,我期望以下工作:
myMongoose.coffee

 mongoose = require 'mongoose' mongoose.connect 'mongodb://localhost/test' @exports = mongoose 

并使用它: MyModel.coffee

 mongoose = require 'myMongoose' console.log mongoose #Prints massive object (including Schema) Schema = mongoose.Schema console.log Schema # undefined 

为什么要像Schema那样访问一个子元素(技术上来说是构造函数,我认为)不起作用? 即使向myMongoose.coffee添加@exports.Schema = mongoose.Schema exports.Schema @exports.Schema = mongoose.Schema mongoose.Schema也不能解决问题。

你必须设置

module.exports = mongoose

您不能用新对象覆盖exports 。 您只能添加属性exports

这是因为你的模块实际上是以下内容:

 (function(require, module, exports, process) { // your code })(); 

exports只是一个参数,重新分配它什么都不做。

所以如果你想覆盖出口使用module.exports 。 如果你想扩展exports使用exports.Foo

但是,如果您覆盖module.exports ,继续写入module.exports而不是exports是最安全的

+1给雷诺斯的答案,但还有更多的东西你应该知道:

 @ is exports # true! 

所以当你写@exports = mongoose ,这相当于@exports = mongoose

@可能更直观地指向module ,但是这样可以很方便地用@输出一堆东西,特别是如果你想在浏览器中运行相同的代码(其中@指向window和你会愉快地填充全球范围)。