Require dependency of another dependency in node modules

后端 未结 2 1645
灰色年华
灰色年华 2020-12-10 10:43

I\'ve got a simple node app that has single dependency on another app on github. The dependency installs just fine with npm install, but when I try to require s

2条回答
  •  醉话见心
    2020-12-10 11:07

    For a more robust case, which is good in situations such as testing, you can use the following function:

    var Module = require('module');
    var path = require('path');
    
    function requireFrom(self, parent, name) {
      var pPath = Module._resolveFilename(parent, self);
      var m = new Module(pPath, module);
      m.filename = pPath;
      m.paths = Module._nodeModulePaths(path.dirname(pPath));
      return m.require(name);
    }
    

    which can be used as follows

    requireFrom(module, 'github_dependency', 'mongoose')
    

提交回复
热议问题