Require dependency of another dependency in node m

2019-01-26 03:02发布

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 something installed there, it says it's not available. For example, the github app installs Mongoose as a dependency. I thought that this parent app would be able to access that module since it is in a child:

var mongoose = require('mongoose')

The structure looks something like this:

/app
  /node_modules
    /github_dependency [parent module]
      /node_modules
        /mongoose [child module]

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?

2条回答
Deceive 欺骗
2楼-- · 2019-01-26 03:32

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')
查看更多
劳资没心,怎么记你
3楼-- · 2019-01-26 03:40

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').

查看更多
登录 后发表回答