Browse topics

Package type and JavaScript module format

Version
24
Since
12.0.0
Review
Draft

Summary#

Node.js uses a JavaScript file’s extension and its package scope to choose between ES modules (ESM) and CommonJS. For a .js file, the closest enclosing package.json controls the choice when it declares type.

Syntax#

FileModule format
.js with "type": "module"ES module
.js with "type": "commonjs"CommonJS
.mjsES module in any package
.cjsCommonJS in any package

For an ambiguous .js file outside node_modules, Node.js 24 checks for ES module syntax when the closest package.json is missing or has no type. A static import or an export selects ESM. Otherwise, code that is valid CommonJS runs as CommonJS.

Example#

Run the same JavaScript in two package scopes and with both explicit extensions. CommonJS supplies a require function.

sh
(
  set -eu
  temp_root=$(CDPATH= cd -- "${TMPDIR:-/tmp}" && pwd -P)
  work_dir=$(mktemp -d "$temp_root/dlr-nodejs-type-XXXXXXXX")
  trap 'rm -rf -- "$work_dir"' 0
  trap 'exit 1' HUP INT TERM
  cd "$work_dir"
  unset NODE_OPTIONS NODE_COMPILE_CACHE NODE_V8_COVERAGE

  printf '%s\n' '{"type":"module"}' > package.json
  mkdir legacy
  printf '%s\n' '{"type":"commonjs"}' > legacy/package.json

  printf '%s\n' 'console.log(process.argv[2], typeof require);' > check.js
  cp check.js legacy/check.js
  cp check.js check.cjs
  cp check.js legacy/check.mjs

  node check.js module-js
  node legacy/check.js commonjs-js
  node check.cjs forced-commonjs
  node legacy/check.mjs forced-esm
)

Expected output#

Text
module-js undefined
commonjs-js function
forced-commonjs function
forced-esm undefined

Common mistakes#

Set type explicitly in each package you maintain. A nested package.json starts a new scope, so a root type can stop applying in a subdirectory. Dynamic import() alone leaves a file eligible for CommonJS.

Version applicability#

Node.js 12.0.0 introduced the type field. The example works without experimental flags starting with 12.17.0 in the 12.x line and 13.2.0 in the 13.x line. Syntax detection arrived in 20.10.0 and 21.1.0 and is on by default from 20.19.0 in the 20.x line and 22.7.0 in the 22.x line.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0