在节点js模块中传递节点间依赖性

时间:2015-04-21 06:50:24

标签: javascript node.js

将依赖项传递给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();
    }
}

1 个答案:

答案 0 :(得分:0)

您发布的代码有效,因为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();