TExcelTAD

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:

  1. <dir of the importing file>/node_modules/lodash
  2. <parent>/node_modules/lodash
  3. … 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:

bash · try it yourself
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

js · try it yourself
// 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:

bash · try it yourself
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 code
CommonJS 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 same node_modules that Node runs from.

Test yourself

A file in /proj/src/deep requires 'greet'. Which folder does Node check first?

  1. /proj/node_modules/greet
  2. /proj/src/deep/node_modules/greet
  3. /node_modules/greet
  4. The registry

A package's exports map lists only "." and "./package.json". What happens on require('pkg/lib/internal.js')?

  1. It works because the file exists
  2. It fails with ERR_PACKAGE_PATH_NOT_EXPORTED
  3. Node falls back to main
  4. npm reinstalls the package

How can npm install two versions of the same package in one project?

  1. It renames one of them
  2. It nests the second version in the node_modules folder of the package that needs it
  3. It cannot
  4. It stores them in package-lock.json