How to Use one module feature within another modul

2019-03-05 23:29发布

问题:

I want to use one module feature within another module

file main.js

var _ = require("./underscore.js");
var foo = require("./bar.js");
foo.publish(...);

file 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

回答1:

Yes, you should use in every module which needs that variable, for the case of you example.

var _ = require("./underscore.js");

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");

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;
}

In main.js:

var _ = require("./underscore.js");
var foo = require("./bar.js")(_);
foo.publish(...);

I hope you got the point.



回答2:

The variable to which you assign the result is local to the module main.js, so you can't access it in bar.js. Instead, you should require the underscore module in bar.js as well.

You could also skip the var when declaring _ and make it a global variable, but that brings all the problems of global variables, like:

  • the bar.js module is not explicit about its dependencies, so it's harder to understand that it expects underscore to be required globally;
  • it requires a specific initialization order - if you later move the _ = require(underscore), you'll get undefined errors again, and it might be hard to understand why;
  • every other module that requires bar.js needs to also require underscore.