Sub topic 7
Running Modules in Node.js
This chapter assumes you already know the import and export syntax from earlier chapters and how module specifiers work in general. You should also be comfortable running node from a terminal and editing a package.json file. Here the question is narrower: when Node.js loads a file, how does it decide whether to treat it as an ES module, and how does a package control what other code may import from it?
Node.js Has Two Module Systems
Node.js supports two module formats. CommonJS is the original format and uses require() and module.exports. ES modules use import and export. Both can coexist in the same project, but Node.js must pick one format for each file before it parses that file. The syntax rules, the available globals, and the resolution rules all depend on that choice.
Node.js does not guess from the contents first. It looks at the file extension and, for .js files, at the nearest package.json.
How Node.js Chooses the Format
| File extension | Format | Depends on package.json? |
|---|---|---|
| `.mjs` | ES module | No, always ESM |
| `.cjs` | CommonJS | No, always CommonJS |
| `.js` | Set by the `"type"` field of the nearest `package.json` | Yes |
| `.json` | JSON (ESM needs an import attribute) | No |
For a .js file, Node.js walks up the directory tree from the file and stops at the first package.json it finds. If that file contains "type": "module", the .js file is an ES module. If it contains "type": "commonjs", or has no "type" field at all, the file is CommonJS.
The last branch is syntax detection. Since Node.js 22.12 (and 20.19 on the 20.x line), a .js file with no explicit "type" that fails to parse as CommonJS because it uses import or export gets parsed again as an ES module. Treat this as a fallback rather than something to rely on. Detection costs an extra parse. Node.js may also print a warning when a package.json exists without a "type" field, and older Node.js versions throw instead of detecting. Set "type" explicitly.
A Minimal ES Module Package
Create this layout:
geometry/
package.json
src/
index.js
math.js
test.jsThe package.json sets the format and the public entry point:
{
"name": "geometry",
"version": "1.0.0",
"type": "module",
"exports": {
".": "./src/index.js"
}
}src/math.js holds the implementation:
// src/math.js
export const PI = 3.14159;
export function area(radius) {
return PI * radius * radius;
}src/index.js is the entry point. Note the full file name in the specifier:
// src/index.js
export { PI, area } from './math.js';test.js imports the package by its own name. Node.js lets a package refer to itself this way as long as it defines "exports":
// test.js
import { area } from 'geometry';
import { readFileSync } from 'node:fs';
const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
console.log(pkg.name, area(2).toFixed(2));Run it from the geometry directory:
node test.jsThe output is geometry 12.57. The node: prefix on node:fs marks a built-in module explicitly. It works for every built-in and cannot be shadowed by a package of the same name on disk, so use it.
Resolution Rules That Differ from CommonJS
In CommonJS, require('./math') tries ./math.js, ./math.json, and ./math/index.js until one exists. The ES module loader does none of that. Relative and absolute specifiers must name the exact file, extension included.
import { area } from './math.js'; // works
import { area } from './math'; // ERR_MODULE_NOT_FOUND
import * as all from './src'; // ERR_UNSUPPORTED_DIR_IMPORTThis matches how browsers resolve URLs, which is the intent. A specifier in ESM is a URL fragment, not a search pattern. If you are converting CommonJS code, adding extensions to every relative import is usually the bulk of the work.
Bare specifiers such as 'geometry' or 'lodash-es' still go through node_modules lookup. When the target package has an "exports" field, that field decides which file is loaded.
The exports Field
The "exports" field defines a package's public interface. It does two jobs:
- It maps the specifiers that consumers write to files inside the package.
- It blocks every path it does not list.
The second job is the one that surprises people. With the package.json above, import 'geometry/src/math.js' fails with ERR_PACKAGE_PATH_NOT_EXPORTED, even though the file exists. You can reorganize the internals freely because nobody outside the package can depend on them.
Subpath Exports
To expose more than one entry point, add keys that start with ./:
{
"name": "geometry",
"type": "module",
"exports": {
".": "./src/index.js",
"./units": "./src/units.js",
"./shapes/*": "./src/shapes/*.js"
}
}Consumers can now write import ... from 'geometry/units' and import ... from 'geometry/shapes/circle'. The * pattern substitutes the matched text into the target path, so geometry/shapes/circle maps to ./src/shapes/circle.js. Consumers never write .js for these subpaths because the mapping supplies it.
Conditional Exports
A package can serve different files depending on how it is loaded:
{
"name": "geometry",
"type": "module",
"exports": {
".": {
"import": "./src/index.js",
"require": "./dist/index.cjs",
"default": "./src/index.js"
}
}
}Node.js checks the conditions in the order they appear in the object, top to bottom, and uses the first match. "import" matches import statements and import(). "require" matches require(). "default" matches anything and must come last, or it will hide the conditions after it. Shipping two separate builds like this carries a risk: if one program loads both copies, it ends up with two instances of the package and two copies of its state. The CommonJS interop chapter covers that problem.
Globals You No Longer Have
ES modules in Node.js run in strict mode with module scope, as in browsers. The CommonJS wrapper variables do not exist:
| CommonJS name | In an ES module |
|---|---|
| `require` | Not defined; use `import`, or `createRequire` (see the CommonJS chapter) |
| `module`, `exports` | Not defined; use `export` |
| `__filename` | Use `import.meta.filename` (Node 20.11+) |
| `__dirname` | Use `import.meta.dirname` (Node 20.11+) |
If you reference one of these, you get ReferenceError: require is not defined in ES module scope. The import.meta chapter covers the replacements in detail.
Common Errors and Their Causes
| Error | Usual cause | Fix |
|---|---|---|
| `SyntaxError: Cannot use import statement outside a module` | A `.js` file is being loaded as CommonJS | Add `"type": "module"` or rename to `.mjs` |
| `ERR_MODULE_NOT_FOUND` on a relative path | Missing file extension | Write `./file.js` |
| `ERR_UNSUPPORTED_DIR_IMPORT` | Importing a folder | Import `./folder/index.js` explicitly |
| `ERR_PACKAGE_PATH_NOT_EXPORTED` | Deep import into a package with `"exports"` | Use a listed subpath, or ask the package to export it |
| `ReferenceError: __dirname is not defined` | CommonJS global used in ESM | Use `import.meta.dirname` |
Exercise
A project's package.json has no "type" field. It contains app.js, which uses import statements, and tool.cjs. A developer adds "type": "module". Which files change format, and what must they do if app.js imports './helpers' (a file named helpers.js)?
Show answer
Only app.js and any other .js files are affected. They are now always ES modules instead of depending on syntax detection or defaulting to CommonJS. tool.cjs stays CommonJS because the .cjs extension overrides "type". The import must become './helpers.js', because the ES module loader does not add extensions.
Exercise
A package's exports field is { ".": "./src/index.js", "./units": "./src/units.js" }. Which of these succeed: import 'pkg', import 'pkg/units', import 'pkg/units.js', import 'pkg/src/units.js'?
Show answer
'pkg' and 'pkg/units' succeed. 'pkg/units.js' and 'pkg/src/units.js' both fail with ERRPACKAGEPATHNOTEXPORTED, because only the exact listed keys "." and "./units" are public.
Exercise
In a conditional exports object, why does placing "default" before "import" cause the "import" target to be ignored?
Show answer
Node.js checks the conditions in the order they appear in the object and uses the first one that matches. "default" matches every load, so when it comes first, Node.js never reaches "import".