iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Modules

A module is a JavaScript file with its own scope, that explicitly exports values and imports them in other files. ES Modules (ESM) are the standard.

Exporting

math.js
// Named exports — any number of them
export const PI = 3.14159;
export function area(r) { return PI * r * r; }

// Or batched at the bottom
const PI2 = 3.14159;
function area2(r) { return PI2 * r * r; }
export { PI2, area2 };

// Default export — one per file
export default function circumference(r) { return 2 * PI * r; }

Importing

app.js
// Named imports
import { PI, area } from "./math.js";

// Rename on the way in
import { area as circleArea } from "./math.js";

// Default import — pick your own name
import circumference from "./math.js";

// Both at once
import circumference, { PI, area } from "./math.js";

// Everything as a namespace
import * as math from "./math.js";
math.PI; math.area(5);

// Side-effect only (runs the file, imports nothing)
import "./setup.js";

Loading in HTML

HTML
<script type="module" src="app.js"></script>
Modules give you…
Their own scope (no globals leaking).
Strict mode by default.
Top-level await.
Static analysis — bundlers can tree-shake unused exports.
Implicit deferred loading.

Dynamic import()

JS
// Load on demand — returns a Promise
button.addEventListener("click", async () => {
  const { showModal } = await import("./modal.js");
  showModal();
});
Tip: Default exports look convenient but hurt refactors — every importer can pick their own name. Prefer named exports unless a module truly represents "one thing".

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Modules!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Mark a script tag so the browser treats it as an ES module.

<script ="module" src="app.js"></script>

Test yourself

Q1. Load JavaScript as a module with…
Q2. A file can have how many default exports?
Q3. Dynamic `import("./x.js")` returns…

Discussion

Loading…