JavaScript Modules
As programs grow, keeping everything in one file becomes unmanageable. Modules let you split code into separate files, each with its own scope. A module decides what to share with export, and other modules pull in what they need with import. ES modules (ESM) are the standard module system for both browsers and Node.js.
Exporting
There are two kinds of exports. A module can have many named exports and at most one default export:
// math.js
export const PI = 3.14159;
export function circleArea(r) {
return PI * r * r;
}
function secretHelper() {} // not exported: private to this file
export default function square(x) {
return x * x;
}You can also export a list at the end of the file, optionally renaming:
const VERSION = "1.2.0";
function format(n) { return n.toFixed(2); }
export { VERSION, format as formatNumber };Importing
// main.js
import square, { PI, circleArea } from "./math.js"; // default + named
import { formatNumber as fmt } from "./utils.js"; // rename on import
import * as math from "./math.js"; // everything as an object
console.log(square(4), circleArea(1), math.PI);| Syntax | Imports |
|---|---|
import x from "./m.js" |
the default export, under any name you choose |
import { a, b } from "./m.js" |
named exports, by their exact names |
import { a as alias } from "./m.js" |
a named export, renamed |
import * as m from "./m.js" |
all exports as a namespace object |
import "./m.js" |
just run the module (side effects) |
await import("./m.js") |
load dynamically, at runtime |
Trying it in a playground
A playground is a single file, but we can still try real import syntax. A data: URL can hold a whole module's source code, and dynamic import() loads it just as it would load a file:
const source = `
export const PI = 3.14159;
export function circleArea(r) { return PI * r * r; }
export default function square(x) { return x * x; }
`;
const url = "data:text/javascript," + encodeURIComponent(source);
const mod = await import(url);
console.log(Object.keys(mod).sort());
console.log(mod.default(5));
console.log(mod.circleArea(2).toFixed(2));
const { PI, default: sq } = mod; // destructure the namespace
console.log(PI, sq(3));[ 'PI', 'circleArea', 'default' ]
25
12.57
3.14159 9
Notice the namespace object: named exports appear under their names, and the default export under the key default.
Modules have their own scope
Top-level variables in a module are not global — they're private to that module unless exported. Each module is also evaluated only once, no matter how many times it's imported, so all importers share the same instance:
const counterSource = `
let count = 0;
export function next() { return ++count; }
`;
const url = "data:text/javascript," + encodeURIComponent(counterSource);
const first = await import(url);
const second = await import(url); // same URL -> same module instance
first.next();
first.next();
console.log(second.next());
console.log(first === second);
console.log(typeof count); // module variables stay private3
true
undefined
Modules in the browser
Load a module with type="module". Module scripts are deferred automatically, always in strict mode, and can use top-level await:
<script type="module" src="./main.js"></script>
<script type="module">
import { circleArea } from "./math.js";
document.body.textContent = circleArea(2);
</script>Things to know:
- Import paths in browsers need the file extension (
./math.js) or a full URL; bare names like"lodash"need an import map or a bundler. - Modules must be served over HTTP(S). Opening
index.htmldirectly from disk (file://) blocks them — use a dev server such as Vite. - In Node.js, use the
.mjsextension or"type": "module"inpackage.json.
Dynamic import
import() returns a promise, so you can load code only when it's needed — for example, a heavy chart library when the user opens the statistics page:
button.addEventListener("click", async () => {
const { drawChart } = await import("./charts.js");
drawChart(data);
});Bundlers like Vite automatically split dynamically imported modules into separate files.
Tip: Prefer named exports in most code: they're easier to search for, auto-import in editors works better, and renaming is explicit. Use a default export when a module clearly has one main thing (a class or a component).
Test yourself
How many default exports can a module have?
- None
- At most one
- Exactly two
- Unlimited
Which statement imports the named export sum from ./calc.js?
- import sum from "./calc.js"
- import { sum } from "./calc.js"
- require("./calc.js").sum
- import * from "./calc.js"
What does import() (dynamic import) return?
- The module object directly
- A promise of the module namespace
- A string
- undefined