Browse topics

JavaScript ES modules

Version
es2025
Since
es2015
Review
Draft

Summary#

An ES module can export named bindings and one default value. Static imports make those exports available before the importing module runs. A dynamic import() returns a promise for the module namespace.

Syntax#

js
// sequence.mjs
export { sequence };
export default reserve;

// report.mjs
import reserve, { sequence } from "./sequence.mjs";
const pending = import("./sequence.mjs");

Example#

Run this shell example with Node.js on your path.

sh
(
  set -eu
  work_dir=$(mktemp -d "${TMPDIR:-/tmp}/dlr-js-ts-core-XXXXXXXX")
  trap 'rm -rf -- "$work_dir"' 0
  trap 'exit 1' HUP INT TERM
  cd "$work_dir"
  unset NODE_COMPILE_CACHE

  cat > sequence.mjs <<'JS'
export let sequence = 0;
export default function reserve() {
  sequence += 1;
}
JS

  cat > report.mjs <<'JS'
import reserve, { sequence } from "./sequence.mjs";
reserve();
console.log(sequence);
JS

  node report.mjs
)

Expected output#

Text
1

Common mistakes#

SyntaxError: Cannot use import statement outside a module means that the file was loaded as a script, not as a module. Node.js does this for a .cjs file, or a .js file whose nearest package.json sets "type": "commonjs". Use the .mjs extension or set "type": "module". In a browser, load the file with the script type module.

Use braces for named imports and include the file extension on relative imports in Node.js. An imported binding reflects changes made by the exporting module. To change it, call a function the exporter provides.

Version applicability#

ES2015 added static import and export, which the JavaScript in the example uses. ES2020 added import(). Node.js loads the example's .mjs files without flags from 12.17.0 in the 12.x line and from 13.2.0 in the 13.x line.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0