質問

I have two node projects who use the same directory:

projectA/
 |- app.js 
 |- projectB/
     |- app.js  
     |- node_modules/ 
           |- moduleX : version 1
 |- commonDir/ 
   |- commonModule.js
 |- node_modules/ 
   |- moduleX : version 2

commonModule.js:

    require("moduleX")

Both projectA and projectB do require(commonModule). I expected that when I run projectA ( "node app" form 'projectA/'), version 2 will be loaded, and when I run projectB("node app" form 'prjoctB/') version 1 will be loaded. Unfortunately, in both cases it seems to run version 2.

Am I doing something wrong here?

EDIT: I understand now that the node searches for the module according to the current module which did the 'require()', which make sense..

So, how can I choose on loading, which module version to run?

役に立ちましたか?

解決

Instead of hard-coding a module name in commonModule I'd set it so that I can give it a module object. For instance commonModule could contain:

module.exports = function(other_module) {
    return {
        foo: function () {
            return other_module.something("blah");
        }
    };
}

Then each project would then pass their own module to commonModule:

var commonModule = require("commonModule")(require("./moduleX"));

commonModule.foo();

./moduleX would be resolved according to each project, so no problem there. Your projects would have to be able to find commonModule but it seems you've already have this part covered.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top