Modules
As a program grows, one huge file becomes hard to manage. ES modules let you split code into separate files, each with its own private scope, and share only what you choose using export and import. Every modern framework and build tool is built on them.
A module is just a file
Each JavaScript file loaded as a module has its own scope: its top-level variables and functions are private unless you export them. Another module can then import exactly what it needs. Here is a small shop project with three files:
shop/ ├── index.html ├── main.js ├── cart.js └── format.js
Named exports
Put export in front of any declaration you want to share. A file can have as many named exports as it likes.
// cart.js
export const VAT_RATE = 0.16;
export function totalWithVat(items) {
const subtotal = items.reduce((sum, item) => sum + item.price * item.qty, 0);
return Math.round(subtotal * (1 + VAT_RATE));
}
function secretDiscount() { // not exported: private to cart.js
return 0;
}
Import named exports with curly braces, using the exact same names:
import { totalWithVat, VAT_RATE } from "./cart.js";
You can also export a list at the bottom of a file, export { totalWithVat, VAT_RATE };, and rename while importing: import { totalWithVat as total } from "./cart.js";.
Default exports
A module can also have one default export, usually the main thing the file provides. You import it without braces, and you may call it anything you like.
// format.js
export default function formatKES(amount) {
return `KES ${amount.toLocaleString("en-KE")}`;
}
// main.js
import formatKES from "./format.js";
import { totalWithVat, VAT_RATE } from "./cart.js";
const items = [
{ name: "Notebook", price: 250, qty: 2 },
{ name: "Calculator", price: 500, qty: 1 }
];
console.log("VAT rate:", VAT_RATE);
console.log(formatKES(totalWithVat(items)));
The subtotal is 250 × 2 + 500 = 1,000, and adding 16% VAT gives 1,160.
main.js, sees its imports, and fetches cart.js and format.js too. Each file only sees what it imports.To grab everything a module exports as one object, use a namespace import: import * as cart from "./cart.js"; then cart.VAT_RATE and cart.totalWithVat(items).
| Named export | Default export | |
|---|---|---|
| How many per file | Any number | At most one |
| Export | export function total() {} | export default function () {} |
| Import | import { total } from "./cart.js" | import anyName from "./format.js" |
| Name must match? | Yes (or rename with as) | No |
Loading modules in the browser
Tell the browser that your entry file is a module with type="module". You only need to include the entry point; the browser follows the imports and loads the other files itself.
<script type="module" src="main.js"></script>
Module scripts behave differently from classic scripts:
- They are deferred automatically: they run after the HTML has been parsed, even if the tag is in the
<head>. - They always run in strict mode, and top-level
thisisundefined. - Top-level variables stay inside the module; they don't become globals.
- Each module runs only once, however many files import it.
- You can use
awaitat the top level of a module.
Modules need a server
If you double-click index.html and it opens with a file:// address, module scripts are blocked and the console shows an error mentioning CORS and the origin 'null'. Browsers only load modules over http:// or https://. Run a small local server from your project folder instead, for example:
npx serve . # or, if you have Python installed: python -m http.server 8000
Then visit the address it prints (such as http://localhost:8000). In VS Code, the Live Server extension does the same with one click.
Leaving out the path or extension. In the browser, import { total } from "cart" fails; you must write a relative path with the extension: "./cart.js". (Bundlers and Node.js packages allow bare names like "react", but plain browser modules don't.) Also watch the braces: import { formatKES } from "./format.js" fails when formatKES is a default export.
Loading a module only when needed
The import() function loads a module on demand and returns a promise. It is useful for large features most users never open:
document.querySelector("#report").addEventListener("click", async () => {
const { drawChart } = await import("./chart.js");
drawChart();
});
Try it: module behaviour
A single preview can't hold several files, but it can run an inline module. This one sits in the <head> yet still finds the paragraph (modules are deferred), shows that top-level this is undefined, and uses top-level await.
<!DOCTYPE html>
<html>
<head>
<script type="module">
const out = document.querySelector("#out");
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
out.textContent = `Found the paragraph. Top-level this is ${this}.`;
await wait(1000);
out.textContent += " One second later: top-level await works!";
</script>
</head>
<body>
<p id="out">Loading...</p>
</body>
</html>
Key points
- Each module file has its own scope; share code with
exportand use it withimport. - Named exports use braces and matching names; a file's single default export is imported without braces under any name.
- Load the entry file with
<script type="module">; modules are deferred, strict and run once. - Browser imports need paths like
"./cart.js", and modules must be served over http(s), not opened fromfile://.
Tip: use the ← and → keys to move between pages.
