要求节点模块中另一个依赖项的依赖项

[英]Require dependency of another dependency in node modules


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:

我有一个简单的节点应用程序,它对github上的另一个应用程序具有单一依赖性。使用npm install时,依赖项安装得很好,但是当我尝试在那里安装某些东西时,它说它不可用。例如,github应用程序将Mongoose安装为依赖项。我认为这个父应用程序将能够访问该模块,因为它在一个孩子:

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?

我是否只需要在父应用程序中包含mongoose作为依赖项,或者是否有办法通过子进程访问该模块?

2 个解决方案

#1


31  

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?

我是否只需要在父应用程序中包含mongoose作为依赖项,或者是否有办法通过子进程访问该模块?

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

虽然你有可能例如require('github / node_modules / mongoose'),标准做法是明确地安装所有依赖项(即,应该包括mongoose作为应用程序的依赖项)和require('mongoose')。

#2


2  

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')
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2012/03/16/17b4fbd26880c013565b6e679d16297f.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告