Skip to content

Instantly share code, notes, and snippets.

@listochkin
Last active March 11, 2017 06:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save listochkin/d829ec886c044eff53ab to your computer and use it in GitHub Desktop.
Save listochkin/d829ec886c044eff53ab to your computer and use it in GitHub Desktop.
How Node Resolves Dependencies

How Node Resolves Dependencies

Read more about node_modules and how you can use them in official node/iojs docs:

If the module identifier passed to require() is not a native module, and does not begin with '/', '../', or './', then io.js starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location.

If it is not found there, then it moves to the parent directory, and so on, until the root of the file system is reached.

Here I show you how you can easily build a hierarchy of modules inside your project and use nested node_modules directories to manage dependencies within your application. This is a pretty good solution that doesn't require you to change NODE_PATH, use many git repositories or setting up a private registry.

/node_modules
| 3rd-party modules: Request, Chalk, etc.
/src
index.js
| // this is your main file
| var a = require('component-a'),
| b = require('component-b');
/node_modules
/component-a
index.js
| var x = require('subcomponent-x'), // see, no paths!
| y = require('subcomponent-y'),
| common = require('common-subcomponent-that-a-and-b-use'),
| request = require('request');
/node_modules
/subcomponent-x
index.js
/node_modules
nest as deep as you like
/subcomponent-y
my-custom-name.js
| // if you don't want to have many index.js files
package.json
| {
| "name": "subcomponent-y",
| "main": "./my-custom-name.js"
| }
/component-b
index.js
/node_modules
| you can put 3rd party modules here, too!
/common-subcomponent-that-a-and-b-use
index.json
| { "you-can": "require json files, too" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment