Why is there a difference between the node_modules folder of a project installed locally vs globally?

Viewed 374

Let's say I have a project with a dependency, A.

A has its own dependency on B.

If I npm install A into my project, my node_modules folder looks like the following. Note that B has been installed as a top level module:

/myproject
    /node_modules
        /A
        /B

Then if I were to depend on myproject from anotherproject, my node_modules folder looks like this:

/anotherproject
    /node_modules
        /myproject
        /A
        /B

But, if I were to install myproject as a global module npm install -g myproject, the node_modules folder ends up looking like this (no top-level B):

/myproject
    /node_modules
        /A

Why is this?

(npm 6.14.4}

1 Answers

This happens because when you install lib A into your project, A will be saved in your project package.json as an dependency and inside A´s owns package.json there is B as an dependency, which will be installed as well but will not be saved into your package.json. When you import your project locally to another project, all modules will have their dependencies check, so because B is into A dependencies, B will be added too. But, when you run a command to install globally, only package.json is going to be verified (not checking the dependencies of your dependencies), then B is not added.

Related