将依赖项传递给nodejs模块的最佳方法是什么?我正在使用gulp browserify,并且具有以下代码设置。
index.js
var a = require('./a.js');
var b = require('./b.js');
b.test(a);
a.js
module.exports = {
foo: function() {
console.log('Foo called!');
}
}
b.js
module.exports = {
bar: function() {
console.log('Bar called!');
},
test: function(a) {
a.foo();
}
}
最佳答案
您发布的代码有效,因为b
不直接依赖a
。
如果b
确实依赖于a
(例如,您需要在a.doSomething()
内部调用b
),则b
应该依赖于a
:
//a.js
exports.doSomething = function() {
// do the thing!
}
--
// b.js
var a = require('./a');
a.doSomething();