ES Modules
An ES module is a JavaScript file that has its own private scope and shares code with other files only through export and import. Modules are how real applications are organized: one file for money formatting, one for the fee rules, one for the user interface, each importing exactly what it needs. Standardized in ES2015, modules now work natively in every browser and in Node.js, replacing older patterns such as global variables, IIFEs and CommonJS require.
In One Minute
- Each module file has its own scope: top-level variables are private unless exported.
- Named exports:
export function format() {}, imported withimport { format } from "./money.js". - Default export:
export default class Tracker {}, imported with any name:import Tracker from "./tracker.js". import * as money from "./money.js"imports everything as a namespace object.- Modules are strict, run once, are deferred in browsers, and support top-level
await.
Exporting and Importing
Named Exports
A module exports values by name; another module imports them by the same names, in braces:
export const CURRENCY = "USD";
export function toCents(dollars) {
return Math.round(dollars * 100);
}
export function formatCents(cents) {
return new Intl.NumberFormat("en-US", { style: "currency", currency: CURRENCY }).format(cents / 100);
}
const internalHelper = () => "not exported"; import { toCents, formatCents, CURRENCY } from "./money.mjs";
const fees = [120, 85.5, 45];
const total = fees.map(toCents).reduce((a, b) => a + b, 0);
console.log(formatCents(total), CURRENCY);
console.log(typeof internalHelper);$250.50 USD
undefinedExplanation: money.js exports three names; app.js imports them. internalHelper isn't exported, so it is invisible outside its module, even though it's at the top level. (This site's checker saves module examples with an .mjs extension, which is why the import says ./money.mjs; in your own project, you'd import ./money.js.)
Export Styles
| Syntax | Meaning |
|---|---|
export const x = 1; export function f() {} export class C {} | Export a declaration |
export { a, b }; | Export existing names (often at the end of the file) |
export { a as alias }; | Export under a different name |
export default value; | The module's default export (one per module) |
export { x } from "./other.js"; | Re-export from another module |
export * from "./other.js"; | Re-export all named exports |
Import Styles
| Syntax | Meaning |
|---|---|
import { a, b } from "./m.js"; | Named imports |
import { a as alias } from "./m.js"; | Rename on import |
import Default from "./m.js"; | The default export, under any name |
import Default, { a } from "./m.js"; | Both |
import * as ns from "./m.js"; | Everything, as a namespace object |
import "./m.js"; | Run the module for its side effects only |
Default Exports
A module can have one default export, typically its main class or function. The importer chooses the name:
export default class FeeTracker {
#payments = [];
add(amount) { this.#payments.push(amount); return this; }
get total() { return this.#payments.reduce((a, b) => a + b, 0); }
}
export const VERSION = "2.1.0"; import Tracker, { VERSION } from "./tracker.mjs";
import * as trackerModule from "./tracker.mjs";
console.log(new Tracker().add(120).add(85).total, VERSION);
console.log(Object.keys(trackerModule).sort());
console.log(trackerModule.default === Tracker);205 2.1.0
[ 'VERSION', 'default' ]
trueA namespace import shows that a default export is simply an export named default.
Renaming and Namespaces
import { formatCents as usd, toCents } from "./money.mjs";
import * as money from "./money.mjs";
console.log(usd(toCents(19.99)));
console.log(money.formatCents(money.toCents(45)));
try {
money.CURRENCY = "EUR";
} catch (err) {
console.log(err.name, "| still", money.CURRENCY, "| frozen?", Object.isFrozen(money));
}$19.99
$45.00
TypeError | still USD | frozen? falseRenaming avoids clashes between modules that export the same name. A namespace object is read-only from outside: assigning to it throws (modules are strict). Interestingly, Object.isFrozen reports false, because its properties must stay live: the exporting module can still change them, as the next section shows.
Live Bindings
An import is not a copy: it's a live, read-only view of the exported variable. If the exporting module changes the variable, importers see the new value; importers can't assign to it:
export let receiptCount = 0;
export function nextReceipt() {
receiptCount++;
return `R-${1000 + receiptCount}`;
} import { receiptCount, nextReceipt } from "./counter.mjs";
console.log(receiptCount);
nextReceipt();
nextReceipt();
console.log(receiptCount);
try {
receiptCount = 99;
} catch (err) {
console.log(err.name + ": " + err.message);
}0
2
TypeError: Assignment to constant variable.How Modules Behave
| Behavior | Detail |
|---|---|
| Own scope | Top-level declarations are private to the file |
| Strict mode | Always, without "use strict" |
| Run once | Importing the same module from many files runs it once; all share one instance |
| Imports are hoisted | import statements are processed before the module's code runs, wherever they appear |
| Static structure | import/export must be at the top level, with string literal paths, so tools can analyze them |
Top-level await | Allowed; modules that import it wait |
this at the top level | undefined |
import.meta | Information about the current module, such as import.meta.url |
Because a module runs once and is shared, it's a natural place for state shared across an app (a settings object, a cache): every importer gets the same instance.
Modules in the Browser
Load a module with type="module". Modules are deferred automatically (they run after the HTML is parsed) and import other files by relative or absolute URL:
<script type="module" src="/js/app.js"></script>
<script type="module">
import { formatCents } from "/js/money.js";
document.querySelector("#total").textContent = formatCents(25050);
</script>| Rule | Why |
|---|---|
Paths need ./, ../, / or a full URL | A bare name like "money" isn't a URL (import maps can map bare names; next lesson) |
| Include the file extension | The browser doesn't guess .js |
Serve over HTTP, not file:// | Modules are fetched with CORS rules; opening the file directly fails |
| Cross-origin modules need CORS headers | Same as fetch |
<p id="total"></p>
<script type="module">
const money = await import("data:text/javascript," + encodeURIComponent(
'export const formatCents = (c) => new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(c / 100);'
));
document.querySelector("#total").textContent = money.formatCents(25050);
console.log(document.querySelector("#total").textContent);
console.log("top-level this:", this);
</script>$250.50
top-level this: undefined(The checker serves one HTML page, so this example builds a module from a data: URL; in a real site you'd import from a .js file.)
Modules in Node.js
Node.js supports two module systems: ES modules (this lesson) and the older CommonJS (require and module.exports). A file is treated as an ES module when:
- its name ends in
.mjs, or - it ends in
.jsand the nearestpackage.jsonhas"type": "module".
{
"name": "fee-tracker",
"type": "module"
}Built-in Node.js modules are imported with the node: prefix: import { readFile } from "node:fs/promises";. The dynamic imports lesson covers CommonJS and how the two systems interoperate.
In Practice
The Fee Tracker split into modules: a pure rules module, a formatting module, and an entry module that wires them together. Each can be tested and changed on its own:
export const GRACE_DAYS = 10;
export function lateFee(daysLate, { rate = 2, cap = 30 } = {}) {
return Math.min(Math.max(daysLate - GRACE_DAYS, 0) * rate, cap);
}
export function balance(fee, payments) {
return fee - payments.reduce((a, b) => a + b, 0);
} import { lateFee, balance } from "./rules.mjs";
import { formatCents, toCents } from "./money.mjs";
const student = { name: "Srihitha", fee: 450, payments: [200, 150], daysLate: 16 };
const due = balance(student.fee, student.payments) + lateFee(student.daysLate);
console.log(`${student.name}: ${formatCents(toCents(due))} due`);Srihitha: $112.00 dueCommon Mistakes
Missing the extension or ./ in browser imports. import "money" fails. Write import "./money.js".
Opening module pages from file://. Browsers block them. Use a local server.
Expecting import to copy values. Imports are live views of the exporter's variables.
Assigning to an import. Imports are read-only: TypeError.
Interview Corner
What is the difference between named and default exports?
A module can have many named exports, imported by their exact names in braces (renamable with as), and at most one default export, imported without braces under any name. A default export is just an export named default. Named exports are friendlier to tooling and refactoring.
How do ES modules differ from scripts?
Modules have their own top-level scope (no implicit globals), are always strict, are evaluated once and shared, have hoisted static imports, support top-level await, have this === undefined at the top level, are deferred in browsers, and are fetched with CORS.
Practice
Challenge: Create a module validators.js with named exports isZip(text) and isPhone(text), then import both under a namespace and test them.
Show solution
export const isZip = (text) => /^\d{5}(-\d{4})?$/.test(text);
export const isPhone = (text) => /^\(?\d{3}\)?[\s.-]?\d{3}[-.]?\d{4}$/.test(text); Show solution
import * as validate from "./validators.mjs";
console.log(validate.isZip("75201"), validate.isZip("7520"));
console.log(validate.isPhone("(214) 555-0100"), validate.isPhone("555-0100"));true false
true falseKey Takeaways
| Task | Code |
|---|---|
| Named export | export function format() {} |
| Named import | import { format } from "./money.js" |
| Default export / import | export default class X {} / import X from "./x.js" |
| Rename | import { format as usd } from "./money.js" |
| Namespace | import * as money from "./money.js" |
| Re-export | export { format } from "./money.js" |
Was this tutorial helpful?