SkillByAIOpen interactive version →

Lesson 5 / 30

ES Modules in Node

Use ES module import and export in Node with type module, understand static resolution and top-level await.

import / export

Set "type": "module" in package.json, or use a .mjs extension, to use ES module syntax.

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

// app.mjs
import { add } from "./math.mjs";
console.log(add(2, 3));

Output:

5

CommonJS vs ESM

ESM imports are resolved statically and support top-level await; CommonJS require calls are dynamic and synchronous.