Node.js theorytheory 0/50 · 0%
Modules · easy

4. ECMAScript modules (ESM)

import/export syntax and how Node tells the two systems apart.

Node also supports native ES modules using `import`/`export`. You opt in either by naming a file `.mjs`, or by setting `"type": "module"` in `package.json` (in which case `.cjs` opts back into CommonJS).

js
// math.mjs
export function add(a, b) { return a + b; }
export default add;

// index.mjs
import add, { add as add2 } from "./math.mjs";

Unlike `require`, ESM imports are resolved and linked before any code runs (static analysis), which enables tree-shaking by bundlers, and top-level `await` is allowed. ESM and CommonJS can interoperate, but a CommonJS file cannot `require` an ESM file directly — it must use a dynamic `import()`.

Check your understanding

  1. 1. How do you mark a project as using ESM by default?

  2. 2. What can ESM do that CommonJS cannot?

  3. 3. How does a CommonJS file load an ESM module?