如何在Node.js require()中的另一个模块中使用一个模块功能 [英] How to Use one module feature within another module in nodejs require()
问题描述
我想在另一个模块中使用一个模块功能
I want to use one module feature within another module
文件main.js
var _ = require("./underscore.js");
var foo = require("./bar.js");
foo.publish(...);
文件bar.js
(function(e) {
var array = [...];
e.publish = function(t, args) {
_.each(array, function(...) {...});
});
})(exports);
我尝试了几种变体,但是我不确定解决此错误的最佳方法:
I've tried a couple of variations, but I am not sure of the best way around this error:
ReferenceError: _ is not defined
推荐答案
是的,对于您的示例,应该在每个需要该变量的模块中使用.
Yes, you should use in every module which needs that variable, for the case of you example.
var _ = require("./underscore.js");
但是,如果您需要在多个模块之间转移一个对象实例,则可以使用 process 对象将其变为全局对象.但这是不好的做法.
But if you need to transfer one object instance between several modules you can use process object to make it global. But that is BAD practice.
process._ = require("./underscore.js");
在模块之间传递对象实例的好方法是将它们作为函数参数传递,但是您需要更改bar.js以返回工厂函数,而不是对象本身.
Good way to pass object instances between the modules is to pass them as function arguments, but you need to change you bar.js to return a factory function, not an object itself.
module.exports = function(_) {
var e = {};
var array = [...];
e.publish = function(t, args) {
_.each(array, function(...) {...});
});
return e;
}
在main.js中:
var _ = require("./underscore.js");
var foo = require("./bar.js")(_);
foo.publish(...);
我希望你明白这一点.
这篇关于如何在Node.js require()中的另一个模块中使用一个模块功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!