JavaScriptEasy
What are ES6 Modules?
ES modules (ESM) are JavaScript's built-in module system: each file has its own scope, shares code with export, and uses other files' code with import; the structure is static, which enables tooling like tree shaking and fast, parallel loading.
Syntax
- Named exports:
export const sum = .../export { a, b as c }. - Default export:
export default function App() {}(at most one per module). - Imports:
import App, { sum } from "./app.js",import * as utils from "./utils.js". - Re-export:
export { thing } from "./thing.js",export * from "./all.js". - Dynamic:
const mod = await import("./heavy.js"). - JSON (modern runtimes):
import data from "./data.json" with { type: "json" }.
Key properties
- Module scope: no accidental globals.
- Strict mode automatically.
- Evaluated once and cached: all importers share the same instance.
- Live bindings: importers see updates to exported
letvariables, but cannot reassign them. - Static structure: imports are hoisted and resolved before the code runs.
- Top-level
awaitis allowed. - In browsers,
<script type="module">is deferred by default and supports import maps.
ESM vs CommonJS
| ESM | CommonJS | |
|---|---|---|
| Syntax | import / export | require / module.exports |
| Loading | Static, asynchronous | Dynamic, synchronous |
| Tree shaking | Yes | Limited |
| Top-level await | Yes | No |
Node supports both ("type": "module" in package.json, or .mjs). Recent Node versions can also require() ES modules in most cases, easing interop.
Tip
Prefer named exports in shared code: they are easier to refactor, autocomplete and tree-shake.
Code example
js
1// --- math.js ---------------------------------------------------2export const PI = 3.14159;3export function area(r) {4 return PI * r * r;5}6export let calls = 0; // live binding: importers see updates7export function track() {8 calls++;9}10export default class Calculator {11 add(a, b) {12 return a + b;13 }14}1516// --- app.js ----------------------------------------------------17import Calculator, { area, calls, track } from "./math.js";18import * as math from "./math.js"; // namespace import1920track();21track();22console.log(calls); // 2 - live binding, read-only for importers23console.log(area(2), new Calculator().add(1, 2), math.PI);2425// Lazy-load a module only when needed (code splitting)26const { formatReport } = await import("./reports.js");2728// Import JSON with an import attribute (modern runtimes)29import config from "./config.json" with { type: "json" };3031// In HTML:32// <script type="module" src="/app.js"></script> (deferred, strict, own scope)
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.