JavaScript Modules (import and export)
A module is a JavaScript file that shares some of its code with other files using export and import.
Why Modules?
As a project grows, one huge file becomes hard to read. Modules let you:
- Keep each part in its own file:
cart.js,prices.js,ui.js - Hide helper code. Only what you
exportcan be used outside - Avoid name clashes. Every module has its own scope, so two files can both have a variable called
total - Reuse code across projects, and load libraries from npm
Named Exports
Put export before anything you want to share. A file can have many named exports.
Example
// prices.js
export const GST = 0.18;
export function withTax(price) {
return Math.round(price * (1 + GST));
}
export function formatRs(amount) {
return "Rs " + amount.toLocaleString("en-PK");
}
const secretMargin = 0.3; // not exported: private to this fileImport them by the same names, inside curly brackets:
Example
// app.js
import { withTax, formatRs } from "./prices.js";
console.log(formatRs(withTax(25000)));Rs 29,500
Default Export
A file can also have one default export. This is common when a file has one main thing, like a class.
Example
// Cart.js
export default class Cart {
constructor() { this.items = []; }
add(name, price) { this.items.push({ name, price }); }
total() { return this.items.reduce((sum, i) => sum + i.price, 0); }
}When importing a default export, you choose the name and do not use curly brackets:
Example
import Cart from "./Cart.js";
import ShoppingCart from "./Cart.js"; // any name worksImport and Export Syntax
| Code | What it does |
|---|---|
export const x = 1; | Named export |
export { a, b }; | Export existing names at the end of a file |
export default thing; | The default export |
import { a, b } from "./file.js"; | Import named exports |
import { a as alpha } from "./file.js"; | Import and rename |
import thing from "./file.js"; | Import the default export |
import * as tools from "./file.js"; | Everything, as one object: tools.a |
export { a } from "./other.js"; | Re-export from another file |
Using Modules in a Page
Load the starting file with type="module":
Example
<script type="module" src="app.js"></script>Module scripts are different from normal scripts:
| Normal script | Module script |
|---|---|
| Variables become global | Each file has its own scope |
| Runs as soon as it loads | Waits until the HTML is parsed (like defer) |
| Non-strict by default | Always in strict mode |
| Works from a local file | Needs a web server (e.g. VS Code Live Server) |
No import/export | Can use import, export and top-level await |
The file path in import must start with ./, ../ or /, and must include .js in the browser. Build tools like Vite let you skip the extension, but the plain browser does not.
A Module You Can Run
A Try it page cannot hold two files, but you can still see module behaviour. Inside type="module", variables are not global, and you can import a library from a CDN:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script type="module">
import confetti from "https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/+esm";
const out = document.getElementById("demo");
const message = "Module loaded! You passed the exam.";
out.innerHTML = message + "<br>Is 'message' global? " + (typeof window.message !== "undefined");
confetti();
</script>
</body>
</html>Try it Yourself »Module loaded! You passed the exam. Is 'message' global? false
Dynamic import()
import() used like a function loads a module only when needed. It returns a promise. This keeps the first page load small.
Example
document.getElementById("chartBtn").addEventListener("click", async () => {
const { drawChart } = await import("./chart.js");
drawChart();
});The chart.js file is downloaded only when someone clicks the button.
Import Maps
An import map lets you give short names to module URLs, so you can write import confetti from "confetti" instead of a long link:
Example
<script type="importmap">
{
"imports": {
"confetti": "https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/+esm"
}
}
</script>
<script type="module">
import confetti from "confetti";
confetti();
</script>In real projects, tools like Vite, Next.js or Node.js use the same import/export syntax, and handle packages from npm for you.
Exercise
Exercise
A file has: export default function greet() {}. Which import is correct?
