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 let variables, but cannot reassign them.
  • Static structure: imports are hoisted and resolved before the code runs.
  • Top-level await is allowed.
  • In browsers, <script type="module"> is deferred by default and supports import maps.

ESM vs CommonJS

ESMCommonJS
Syntaximport / exportrequire / module.exports
LoadingStatic, asynchronousDynamic, synchronous
Tree shakingYesLimited
Top-level awaitYesNo

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 updates
7export function track() {
8 calls++;
9}
10export default class Calculator {
11 add(a, b) {
12 return a + b;
13 }
14}
15
16// --- app.js ----------------------------------------------------
17import Calculator, { area, calls, track } from "./math.js";
18import * as math from "./math.js"; // namespace import
19
20track();
21track();
22console.log(calls); // 2 - live binding, read-only for importers
23console.log(area(2), new Calculator().add(1, 2), math.PI);
24
25// Lazy-load a module only when needed (code splitting)
26const { formatReport } = await import("./reports.js");
27
28// Import JSON with an import attribute (modern runtimes)
29import config from "./config.json" with { type: "json" };
30
31// 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.

Open in study app