Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I put the npm node_modules directory outside of my project

Tags:

node.js

npm

Can I put the node_modules directory outside my project just the way maven does with its dependencies?

like image 422
Philippe Gioseffi Avatar asked Mar 02 '23 10:03

Philippe Gioseffi


2 Answers

Sort of. The node_modules directory is not actually a feature of npm but a feature of node.js.

How node.js uses node_modules.

When you require a module node.js will search for a node_modules directory from the current directory upwards. That means if it can't find one in the current directory (which may actually be a subdirectory of your project instead of your project directory) it will look for it in the parent directory then the parent's parent all the way to your root directory.

For example, you can have a project structure like this:

/node_modules   <-------------------- modules available to all projects    
/code
     /project_A
                /node_modules <------ modules available to project A
                /lib
                    /node_modules <-- modules available to the lib directory
     /project_B
               /node_modules  <------ modules available to project B

This way you can have some modules shared by multiple projects and some modules that are project specific and even some modules that are only available to some files in your project.

How npm handles node_modules

Note however that npm has only one interpretation of node_modules. It only manages node_modules in your project directory. Specifically the directory that contains the package.json file.

So yes, you can do it but npm won't understand what you are doing and your package.json will contain incomplete dependencies. I wouldn't recommend doing this with projects involving multiple developers because it will look more like a misconfigured development environment - basically others will think this is a bug. However I personally have used such structures for personal projects where I don't care about my package.json file.

like image 196
slebetman Avatar answered Mar 04 '23 22:03

slebetman


As mention in this question Don't do it. Let NPM work the way it's designed to. However, to save space, you can delete the node_modules folder on projects that are currently dormant, and recreate it with a single shot of npm install when you switch back to them.

It is an issue if the plugin declares to install the modules in a configurable directory. Therefore I suggest to fix the documentation, it gives false hopes. Please see npm docs, as this is the default behaviour of npm. Not a frontend-maven-plugin issue.

like image 34
Akash Manujaya Avatar answered Mar 05 '23 00:03

Akash Manujaya