1

For example, I have following structure

main
    -- doTask1
        -- task1-1.js
        -- task1-2.js
    -- doTask2
        -- task2-1.js
        -- task2-2.js

If I run npm install <some package> in doTask1, a new directory node_modules is created in doTask1.

Now in doTask2, I need to use the same package, do I need to run npm install <some package> in doTask2 again? It will create another node_modules in doTask2 which is duplicate. What's the correct way to manage this?

Joe Huang
  • 6,296
  • 7
  • 48
  • 81

1 Answers1

5

NPM resolution of node modules that are not referenced with a relative path, is to first check current directory, and then traverse upwards each directory from current looking for a node_modules folder.

So in your situation, just install in main if you want the same version of the same package / module:

enter image description here

Finally, you could install the required package / module globally - however, this is usually only recommended for packages you know you need from the command line anywhere (for instance gulp, webpack etc). In your situation, for modules specific to the application it is best to keep them locally installed under a node_modules folder.

Some helpful NPM documentation on installing npm packages:

  • See "Loading from node_modules Folders" here
  • A slightly old but relevant blog post here
arcseldon
  • 35,523
  • 17
  • 121
  • 125
  • Thanks for the detailed explanation in a nice format. It's good to know it will traverse upwards looking for the node_modules folder. – Joe Huang Jan 11 '16 at 02:59
  • @JoeHuang - no probs, thanks for acknowledging the answer. Have added a link at the bottom of the answer to some helpful docs which goes into more details if interested. – arcseldon Jan 11 '16 at 03:02
  • 1
    Updated the docs link to a blog which actually better describes the process. – arcseldon Jan 11 '16 at 03:09