Joe Huang
Joe Huang

Reputation: 6570

With node.js, how to manage npm across modules?

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?

Upvotes: 1

Views: 57

Answers (1)

arcseldon
arcseldon

Reputation: 37155

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

Upvotes: 5

Related Questions