In Ubuntu, I have a directory with my code /code
which has my packages.json
and such. My NPM prefix is /usr
via npm prefix -g
. I am trying to install packages globally so as to not create a node_modules
directory in /code
, but really as long as node_modules
is not in /code
, that will also work.
While in /code
, I run npm install -g
. I see a .staging
directory created under my global prefix (eg, /usr/lib/node_modules/.staging
) but then NPM takes another step and begins creating a /code/node_modules
directory.
If I instead just run npm install -g <package>
it correctly ends up in /usr/lib/node_modules/<package>
. But I do not want to have to run npm install -g <package>
for every package I need.
Why is NPM doing that and how can I make it stop doing that? At the very least, I would like the node_modules
directory to NOT be in my /code
directory (this is due to some environment constraints I can't change).
CodePudding user response:
Globally installed packages are (almost always) not going to be used by your code. That's not how node
or npm
(conventionally) works. There isn't a shared global node_modules
that programs all look in. (OK, there kinda is, but you don't want to use it if you can avoid it. Read on.) Having a local node_modules
helps you avoid dependency hell. Global modules are for CLI tools that end up in your PATH
and things like that.
You don't explain why you don't want a local node_modules
for your project, so I will mention that if it is simply because it somehow bothers you, then please please please just get over it. You will be vastly happier. Type npm install
and move on.
That said, for legacy reasons, your code in /code
will look in /node_modules
if there is no /code/node_modules
. This is true for CommonJS modules that use require()
. If you are using ESM modules via import
, you may need to read the docs.
So, if you are using CommonJS/require()
, you could have a directory structure like /project-name/code
. You could have your index.js
or whatever other code in the code
subdirectory, while your package.json
could be in project-name
. Run npm install
from /project-name
and it will create a node_modules
directory there rather than in the code
subdirectory, and your Node.js files in code
will find those modules.
If you don't like that, then for other options, you can review the relevant docs. At the time of this writing, those options include a NODE_PATH
environment variable, $HOME/.node_modules
, $HOME/.node_libraries
, and $PREFIX/lib/node
. However it all comes with this caveat that I implore you to abide by if you can:
It is strongly encouraged to place dependencies in the local node_modules folder. These will be loaded faster, and more reliably.