简体   繁体   中英

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. 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. That way all my projects could search for modules in a relative path like this ../ for example.

Here you can use 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 .

All you need to do is, link all modules in /User/you/modules directory to /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.

So, you can now;

require('package-name')

package-name is taken from package.json , not from directory name.

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.


The below example seems to work well when run as such: NODE_PATH=./lib node app.js

app.js

require('api')();

lib/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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