Advanced JavaScript PatternsLesson 6.1
ES modules: import and export syntax in JavaScript
named exports, default export, import syntax, re-exporting, dynamic import, module scope, circular dependencies, tree shaking, import.meta
Modules Are the Unit of Code Organization
ES Modules (ESM) let you split code across files with explicit import/export. Each module has its own scope โ no global pollution. Modules are cached after the first import.
Named and Default Exports
// math.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export default function multiply(a, b) { return a * b; }
// main.js
import multiply, { PI, add } from "./math.js";
import * as Math from "./math.js"; // namespace import
Math.add(2, 3); // 5
Re-exporting
// index.js โ barrel file
export { add, PI } from "./math.js";
export { formatDate } from "./dates.js";
// consumers import from one place
Dynamic Import
// loads the module only when needed โ returns a Promise
const { default: Chart } = await import("./chart.js");
new Chart(canvas, config);
Key Rules
Modules always run in strict mode. Named exports must be imported with matching names (or aliased with as). A module can have multiple named exports but only one default export. Dynamic import is the correct tool for code-splitting โ load heavy modules only when the user needs them.
