简体   繁体   English

如何在其他目录中重定向对 node_modules 的搜索

[英]How to redirect search for node_modules in other directory

Hi I want to aceess npm modules from directory that is not the current one.嗨,我想从不是当前目录的目录中访问 npm 模块。 The global modules are not solution since the dependency they involve.全局模块不是解决方案,因为它们涉及依赖项。 I want to have a container with all the modules I have downloaded and to redirect require to that directory instead of the current directory.我想要一个包含我下载的所有模块的容器,并将require重定向到该目录而不是当前目录。 That way all my projects could search for modules in a relative path like this ../ for example.这样我所有的项目都可以在相对路径中搜索模块,例如../

Here you can use npm link .在这里你可以使用npm link

For example,例如,

Let's say you have 10 local node package repositories (with package.json inside each package) in /User/you/modules and your project is in /User/you/project .假设您在/User/you/modules有 10 个本地节点包存储库(每个包中有package.json ),并且您的项目在/User/you/project

All you need to do is, link all modules in /User/you/modules directory to /User/you/project .您需要做的就是将/User/you/modules目录中的所有模块链接到/User/you/project

cd /User/you/project
find /User/you/modules/* -type d -maxdepth 0 -exec npm link {} \;

Now, you can use all your modules from /User/you/modules in /User/you/project without relative path.现在,您可以在没有相对路径的情况下/User/you/project /User/you/modules中的所有模块。

So, you can now;所以,你现在可以;

require('package-name')

package-name is taken from package.json , not from directory name. package-name取自package.json ,而不是目录名。

instead of;代替;

require('../modules/package-name')

Cheers.干杯。

You can set the NODE_PATH environment variable before/when running your app and this will allow you to add your own directories to the paths Node tries to resolve packages from.您可以在运行应用程序之前/时设置NODE_PATH环境变量,这将允许您将自己的目录添加到节点尝试从中解析包的路径。


The below example seems to work well when run as such: NODE_PATH=./lib node app.js以下示例在运行时似乎运行良好: NODE_PATH=./lib node app.js

app.js应用程序.js

require('api')();

lib/api.js库/api.js

module.exports = () => console.log('hello');


Here is an interesting Gist which includes some other routes if the above doesn't look appropriate for you.这是一个有趣的要点,其中包括一些其他路线,如果上述路线看起来不适合您。 There is also some interesting discussion in the comments between some of the prominent Node.js folks.在一些著名的 Node.js 人员之间的评论中也有一些有趣的讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM