Require dependency of another dependency in node modules

霸气de小男生 提交于 2019-11-28 11:52:50

Do I just have to include mongoose as a dependency as well in the parent app or is there a way of getting access to that module by way of the child?

While it's possible for you to e.g. require('github/node_modules/mongoose'), the standard practice is to install all of your dependencies explicitly (i.e., you should include mongoose as a dependency of your app) and require('mongoose').

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')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!