/config/nodejs/package-json-type-module
package.json "type": "module": ES modules in Node.js
verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · v24.20.0updated 2026-10-20
- tool
- Node.js
- file
- package.json
- key
- type
- type
- "module" | "commonjs"
- default
- "commonjs"
The "type" field in package.json decides how Node.js loads .js files in that package: "module" makes them ES modules, "commonjs" (the default when the field is missing) makes them CommonJS. .mjs files are always ES modules and .cjs files are always CommonJS, whatever type says.
Example
npm init -y >/dev/null
npm pkg set type=module
echo 'export const greet = (n) => `hello, ${n}`;' > lib.js
echo 'import { greet } from "./lib.js"; console.log(greet("esm")); console.log(typeof require);' > main.js
node main.jsOutput
hello, esm undefined
require is not defined in ES modules. Use import, or createRequire from node:module when you need to load a CommonJS-only file.
What changes with "type": "module"
| "type": "commonjs" (default) | "type": "module" | |
|---|---|---|
| .js files | CommonJS | ES modules |
| import / export | only in .mjs | yes |
| require(), module.exports | yes | only in .cjs |
| __dirname, __filename | yes | use import.meta.dirname / import.meta.filename |
| Relative imports | extension optional | extension required: ./lib.js |
| Top-level await | no | yes |
Pitfalls
- Relative ESM imports need the file extension:
import "./lib"fails withERR_MODULE_NOT_FOUND. - Config files of some tools (for example older
.eslintrc.js) are loaded withrequire; rename them to.cjsafter switching. - The field applies to the folder of that
package.jsonand its subfolders, up to the nextpackage.json.
Sources
Related pages
errors · nodejsError: Cannot find module '…' in Node.jsNode.js throws Cannot find module when require() or import cannot resolve a path or package. Install the package, fix the relative path or add the extension.codes · nodejsNode.js exit codes: 1, 9, 13, 124 and 128+ explainedNode.js exit codes: 1 uncaught exception, 5 fatal V8 error, 9 invalid argument, 13 unsettled top-level await, 124 process timeout, 128+n killed by a signal.cheat sheets · npmnpm cheat sheet: install, run, update, publishnpm cheat sheet: init, install and uninstall, version specifiers, scripts, outdated and update, npm ci for CI, ls and explain, config and cache commands.