我一直在做一个使用一些自定义Node.js模块的项目。我创建了一个“帮助”模块,它帮助加载一些帮助方法:
/helpers/index.js:
var mutability = require('./mutability'),
cb = require('./cb'),
build = require('./build'),
userAgent = require('./userAgent'),
is = require('./is'),
query = require('./query'),
config = require('./config'),
_ = require('underscore')
module.exports = _.extend({
cb: cb,
build: build,
userAgent: userAgent,
is: is,
query: query,
config: config
}, mutability)为了好玩,mutability.js是:
'use strict'
module.exports = {
setReadOnly: function(obj, key) {
// whatever
return obj
},
setWritable: function(obj, key) {
// whatever
return obj
}
}我的一个模块,build,需要一个类来执行某种类型检查:
/helpers/build.js
'use strict'
var urljoin = require('url-join'),
config = require('./config'),
cb = require('./cb'),
Entity = require('../lib/entity'),
_ = require('underscore')
module.exports = {
url: function(options) {
return urljoin(
config.baseUrl,
options.client.orgId,
options.client.appId,
options.type, (typeof options.uuidOrName === 'string') ? options.uuidOrName : ""
)
},
GET: function(options) {
options.type = options.type || args[0] instanceof Entity ? args[0]._type : args[0]
options.query = options.query || args[0] instanceof Entity ? args[0] : undefined
return options
}
}而Entity则需要helpers
/lib/entity.js
'use strict'
var helpers = require('../helpers'),
ok = require('objectkit'),
_ = require('underscore')
var Entity = function(object) {
var self = this
_.extend(self, object)
helpers.setReadOnly(self, ['uuid'])
return self
}
module.exports = Entity无论出于什么原因,当我使用Mocha运行这个程序时,helpers会在{}和Mocha抛出时退出:
Uncaught TypeError: helpers.setReadOnly is not a function当我直接使用/lib/entity.js运行node时,它会打印出适当的模块。怎么回事?为什么摩卡会爆炸?
发布于 2015-12-04 04:29:48
正确的问题是index.js和entity.js之间的循环依赖关系。
依赖关系图如下(具有规范化路径),其中每个箭头都是一个require语句:
/helpers/index.js -> /helpers/build.js -> /lib/entity.js -> /helpers/index.js当一个模块是节点中的required时,module.exports被初始化为一个空对象。
当您有一个循环依赖项时,这个默认对象可能会在您的代码运行到实际设置之前返回到另一个模块(因为JavaScript是同步的)。
这就是在您的情况下所发生的事情:/lib/entity.js在index.js定义它的module.exports = _.extend(...)之前,正在接收来自index.js的默认导出对象。
要修复它,需要确保扩展返回给/lib/entity.js的相同对象,而不是用新实例替换它:
// Extend `module.exports` instead of replacing it with a new object.
module.exports = _.extend(
module.exports,
{
cb: cb,
build: build,
userAgent: userAgent,
is: is,
query: query,
config: config
},
mutability
);但是,如果可能的话,最好避免循环依赖。
https://stackoverflow.com/questions/34079751
复制相似问题