How Node Resolves Packages
Package managers exist to put files where Node will find them. Before comparing npm's flat node_modules, pnpm's symlinks and Yarn's Plug'n'Play, you need the rule they all have to satisfy: what Node does with require('lodash') or import 'lodash'.
The node_modules walk
A bare specifier (lodash, @scope/pkg, not ./file.js or /abs/path) is looked up by walking up the directory tree from the importing file:
<dir of the importing file>/node_modules/lodash<parent>/node_modules/lodash- … up to
/node_modules/lodash
The first folder that exists wins. Inside it, Node reads package.json to find the entry point (exports, or main for older packages, or index.js). That's all: no registry, no versions, no lockfile. Versions only matter to the package manager that arranged the folders.
Here is the walk, by hand, with no package manager at all:
mkdir -p proj/node_modules/greet proj/src/node_modules/greet proj/src/deep
cd proj
echo '{ "name": "greet", "version": "1.0.0", "main": "main.js" }' > node_modules/greet/package.json
echo 'module.exports = "greet 1.0.0 from proj/node_modules";' > node_modules/greet/main.js
echo '{ "name": "greet", "version": "2.0.0" }' > src/node_modules/greet/package.json
echo 'module.exports = "greet 2.0.0 from proj/src/node_modules";' > src/node_modules/greet/index.js
echo 'console.log(require("greet"));' > top.js
echo 'console.log(require("greet"));' > src/deep/inner.js
node top.js
node src/deep/inner.js
node -e 'console.log(require.resolve("greet"))'
node -e 'console.log(module.paths.slice(0, 3))'greet 1.0.0 from proj/node_modules
greet 2.0.0 from proj/src/node_modules
/home/learner/proj/node_modules/greet/main.js
[
'/home/learner/proj/node_modules',
'/home/learner/node_modules',
'/home/node_modules'
]
src/deep/inner.js found the nearer copy first. This is how npm can install two versions of the same package in one project: a conflicting version goes into the node_modules folder inside the package that needs it, so that package's walk finds it first. module.paths shows the list of folders Node tries, nearest first.
A model of the walk
// A fake file system: the folders that exist.
const dirs = new Set([
'/proj/node_modules/greet',
'/proj/src/node_modules/greet',
'/proj/node_modules/chalk',
'/proj/node_modules/chalk/node_modules/ansi-styles',
]);
function candidates(fromDir) {
const parts = fromDir.split('/').filter(Boolean);
const out = [];
for (let i = parts.length; i >= 0; i--) {
if (parts[i - 1] === 'node_modules') continue; // Node skips .../node_modules/node_modules
out.push('/' + [...parts.slice(0, i), 'node_modules'].join('/'));
}
return out;
}
function resolve(name, fromDir) {
for (const nm of candidates(fromDir)) {
if (dirs.has(`${nm}/${name}`)) return `${nm}/${name}`;
}
return `Cannot find module '${name}'`;
}
console.log(candidates('/proj/src/deep'));
console.log(resolve('greet', '/proj/src/deep'));
console.log(resolve('greet', '/proj'));
console.log(resolve('ansi-styles', '/proj/node_modules/chalk'));
console.log(resolve('ansi-styles', '/proj'));[
'/proj/src/deep/node_modules',
'/proj/src/node_modules',
'/proj/node_modules',
'/node_modules'
]
/proj/src/node_modules/greet
/proj/node_modules/greet
/proj/node_modules/chalk/node_modules/ansi-styles
Cannot find module 'ansi-styles'
The last line matters later: a package nested inside chalk is invisible to your own code. A package hoisted to the top is visible to everyone, even code that never declared it. That's the root of the phantom dependency problem.
The entry point: main vs exports
Once Node has found the folder, package.json decides which file you get:
| Field | Meaning |
|---|---|
main |
the file for require('pkg'); any other file is reachable with a deep path (pkg/lib/x.js) |
exports |
a map of the only paths outsiders may import; everything else is private |
exports conditions |
"import", "require", "types", "node", "browser", "default": different files for different consumers |
type |
"module" makes .js files ES modules; "commonjs" (or none) makes them CommonJS |
exports turns the package's folder layout into a public API:
mkdir -p app/node_modules/tool/lib && cd app
cat > node_modules/tool/package.json <<'JSON'
{
"name": "tool",
"version": "1.0.0",
"exports": {
".": { "import": "./lib/tool.mjs", "require": "./lib/tool.cjs" },
"./package.json": "./package.json"
}
}
JSON
echo 'export const kind = "ESM build";' > node_modules/tool/lib/tool.mjs
echo 'exports.kind = "CommonJS build";' > node_modules/tool/lib/tool.cjs
echo 'module.exports = "internal helper";' > node_modules/tool/lib/internal.js
node -e 'console.log(require("tool").kind)'
node --input-type=module -e 'import { kind } from "tool"; console.log(kind)'
node -e 'console.log(require("tool/package.json").version)'
node -e 'require("tool/lib/internal.js")' 2>&1 | grep codeCommonJS build
ESM build
1.0.0
code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
One package, two builds: require got the CommonJS file and import the ES module file. The deep import of lib/internal.js failed with ERR_PACKAGE_PATH_NOT_EXPORTED even though the file exists. Library authors use this to change their internals without breaking anyone; you'll build exactly this kind of dual package with Rollup.
Note: Bundlers implement the same algorithm (plus their own conditions such as
"browser"and"module"), which is why a bundle can be built from the samenode_modulesthat Node runs from.
Test yourself
A file in /proj/src/deep requires 'greet'. Which folder does Node check first?
- /proj/node_modules/greet
- /proj/src/deep/node_modules/greet
- /node_modules/greet
- The registry
A package's exports map lists only "." and "./package.json". What happens on require('pkg/lib/internal.js')?
- It works because the file exists
- It fails with ERR_PACKAGE_PATH_NOT_EXPORTED
- Node falls back to main
- npm reinstalls the package
How can npm install two versions of the same package in one project?
- It renames one of them
- It nests the second version in the node_modules folder of the package that needs it
- It cannot
- It stores them in package-lock.json