Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does node resolve a module location when its required from another module?

I have the following directories and files

/path/to/dir1
/path/to/dir1/server.js
/path/to/dir1/package.json
/path/to/dir1/node_modules

/path/to/dir2/moduleA.js

Then I have moduleA.js which starts like this:

var React = require('react');

And my package.json file looks like this:

{
 "dependencies": {
    "react": "^0.10.0"
  }
}

Now from within server.js if I do this:

require('../dir2/moduleA')

It will find moduleA but then in moduleA I have require('react') which actually resides within the same directory of server.js in the node_modules folder. However this location is not searched and I am getting an error

Error: Cannot find module 'react'

I thought one of the locations searched when resolving require statements was the node_modules directory of the currently executing process? Why is this not working?

like image 1000
asolberg Avatar asked Jul 05 '14 21:07

asolberg


People also ask

Where does NodeJS require look for modules?

Node will look for your modules in special folders named node_modules . A node_modules folder can be on the same level as the current file, or higher up in the directory chain. Node will walk up the directory chain, looking through each node_modules until it finds the module you tried to load.

How do node modules work?

As building blocks of code structure, Node. js modules allow developers to better structure, reuse, and distribute code. A module is a self-contained file or directory of related code, which can be included in your application wherever needed. Modules and the module system are fundamental parts of how Node.

Where does require look for modules?

The require function will look for files in the following order. NPM Modules. It will look in the node_modules folder. Local Modules.


1 Answers

From the documentation:

Loading from node_modules Folders

If the module identifier passed to require() is not a native module, and does not begin with '/', '../', or './', then node 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 tree is reached.

For example, if the file at '/home/ry/projects/foo.js' called require('bar.js'), then node would look in the following locations, in this order:

/home/ry/projects/node_modules/bar.js
/home/ry/node_modules/bar.js
/home/node_modules/bar.js
/node_modules/bar.js

This allows programs to localize their dependencies, so that they do not clash.

I.e. it would look in /path/to/dir2/node_modules, /path/to/node_modules, etc, but not in /path/to/dir1/node_modules.

like image 180
Felix Kling Avatar answered Oct 21 '22 13:10

Felix Kling