treecoder
treecoder

Reputation: 45141

Using NPM & gruntjs build system

I am new to Node.js echo system and trying to set up a build system for JavaScript application development. I have some questions that I can't find answers to.

From this blog post, it is clear that you should install all the project specific node modules locally.

Now, I am installing the entire grunt module locally in my project directory. I get the following directory structure...

my_project/

  lib/
    utils/
      underscore.js

  ... other project files ...

  node_modules/
    .bin/
      grunt -> ../grunt/bin/grunt*
    grunt/
      node_modules/
      bin/
      dev/
      docs/
      lib/
      test/
      tasks/
      grunt.js
      package.json
      ... others ...

Note that there are TWO node_modules directories. One in my project and other inside the grunt module.

Q: Why are there multiple node_modules directories at different levels? Can someone explain me how the directory structure works?

Q: If I install another module, will it also have its own node_modules directory?

Q: If I go within my_project/lib/utils and then run the command npm install <some_module>, will that module be installed only for that directory or for the entire project? If the latter, then how does NPM/Node figure out the project root?

Please explain anything else I might be missing here.

Upvotes: 1

Views: 359

Answers (1)

smithclay
smithclay

Reputation: 3386

Every project in the npm registry can be thought of a self-contained module (specifically, a CommonJS module) that has source code and project metadata defined in a package.json file in the root directory of that project.

When you type npm install (or just npm i) in a directory with a package.json file, npm reads the collection of dependencies defined in package.json in your project's root directory and installs those packages in the node_modules directory.

So what's with the nested node_modules directories? npm install is recursive. If project A requires B and B requires C, you'd see this directory structure:

A/
A/node_modules
A/node_modules/B
A/node_modules/B/node_modules
A/node_modules/B/node_modules/C

In your case, when you add grunt to dependencies in the my_project/package.json file, that dependency will get added to its own directory: my_project/node_modules/grunt. But grunt has a lot of dependencies, and those dependencies have dependencies. So you'll see many nested node_modules directories.

For your third question, see the algorithm section on this page: https://npmjs.org/doc/install.html -- it describes how npm install searches for dependencies.

There's also some more information about global vs local dependencies in npm here.

Upvotes: 4

Related Questions