Modules (import and export)
Part of the Web Development Roadmap
In short
One 3,000-line file is a nightmare to work in. Modules let you split code into small files that share only what they choose, using import and export.
Modules split code into separate files that export what they share and import what they need, keeping large projects organised.

Think of it like this
College departments
Accounts, Library and the Exam cell each run their own work and keep their files private. They share only what's needed through a counter window. export is that counter window. import is you walking up to it and asking.
Watch it happen
Files sharing through import
import { withGst }
1/6app.js asks math.js for its default export and withGst.
The big ideas
What you need to know
Named and default exports
A file can have many named exports and one default. Named ones are imported with curly braces.
Each file has its own scope
Variables in a module aren't global. Other files see only what you export.
type="module" in the browser
Use <script type="module">. Modules run in strict mode and are deferred automatically.
Load later with import()
Dynamic import() loads a module only when you need it, which keeps the first page load smaller.
See it in code
Walk through the code
1// math.js2export const GST = 0.18;3export function withGst(price) {4 return price + price * GST;5}6export default function formatRupees(n) {7 return "₹" + n.toFixed(2);8}9 10// app.js11import formatRupees, { withGst } from "./math.js";12console.log(formatRupees(withGst(100))); // "₹118.00"13 14// Load a heavy module only when the user asks for it15const { drawChart } = await import("./chart.js");1/4Named exports: a constant and a function.
The default import can take any name you like. Named imports must match the exported names, unless you rename them with as.
Save yourself the pain
Common mistakes
Oops
Using import in a normal <script> and getting "Cannot use import statement outside a module".
Do this instead
Add type="module" to the script tag.
Oops
Opening the HTML file by double-clicking it and seeing a CORS error.
Do this instead
Modules don't load over file://. Run a local server, like the VS Code Live Server extension or npx serve.
Your mission
Split a script
Quick check
Three different files import the same module. How many times does that module's top-level code run?
Go deeper
- 1Move helper functions into a utils.js file and import them where needed.
- 2Learn the difference between named exports and a default export.
- 3Load a module in the browser with script type="module".
More topics at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.