As a project grows, keeping all the code in one file becomes hard to manage. Modules let you split code into separate files, each with its own scope, and share only what you choose with export. Other files bring those pieces in with import. Modules are the standard way to organise JavaScript in browsers, in Node.js and in frameworks such as React.
In this lesson you will learn
- Named exports and default exports
- The different forms of
import - Using modules in a web page with
type="module" - Using modules in Node.js
- How modules differ from ordinary scripts
Exporting and Importing
This example has two files. The first is a small library:
mathutils.mjs
// Named exports
export const TAX_RATE = 0.15;
export function addTax(price) {
return Math.round(price * (1 + TAX_RATE));
}
export function formatTaka(amount) {
return `৳${amount.toLocaleString("en-IN")}`;
}
// One default export per module
export default function total(prices) {
return prices.reduce((sum, p) => sum + p, 0);
}
The second file imports from it:
main.mjs
import total, { addTax, formatTaka, TAX_RATE } from "./mathutils.mjs";
import * as utils from "./mathutils.mjs";
const cart = [1200, 450, 80];
const subtotal = total(cart);
console.log("Subtotal:", formatTaka(subtotal));
console.log(`With ${TAX_RATE * 100}% tax:`, formatTaka(addTax(subtotal)));
console.log("Namespace import works too:", utils.addTax(100));
Output of node main.mjs
Subtotal: ৳1,730
With 15% tax: ৳1,989
Namespace import works too: 115
- Named exports (
export const,export function) share several values by name. They are imported in braces with the same names:{ addTax, formatTaka }. - A module can have one default export. It is imported without braces and you choose its local name, here
total. import * as utilsgathers every named export into one object.- Rename on import with
as:import { addTax as withTax } from "./mathutils.mjs". - Anything not exported, such as a helper function, stays private to its file.
Modules in the Browser
<script type="module" src="js/main.js"></script>
// js/main.js
import { formatTaka } from "./mathutils.js";
document.querySelector("#price").textContent = formatTaka(1500);
- Add
type="module"to the script tag. Module scripts are deferred automatically, so they run after the HTML is ready. - Import paths must be full relative paths with the extension, starting with
./or../. - Modules must be served over HTTP. Opening the HTML file directly from disk (
file://) blocks them, so use a local server such as the Live Server extension in VS Code.
Modules in Node.js
Node.js treats .mjs files as modules, as in the example above. To use import in ordinary .js files, add "type": "module" to your package.json. Older Node.js code uses a different system called CommonJS:
// CommonJS (older Node.js style)
const fs = require("fs");
module.exports = { addTax };
// ES modules (modern standard)
import fs from "node:fs";
export { addTax };
How Modules Differ From Scripts
| Classic script | Module | |
|---|---|---|
| Top-level variables | Shared globally | Private to the file |
| Strict mode | Only if requested | Always on |
Top-level await | Not allowed | Allowed |
| Runs | Every time it is included | Once, however many files import it |
Common Mistakes
- Leaving out
type="module", causing “Cannot use import statement outside a module”. - Missing the
./or the file extension in browser import paths. - Using braces for a default import or no braces for a named one.
- Opening the page from
file://and getting CORS errors for module files.
Practice Exercises
Exercise 1. Create greet.js that exports a default function greet(name), and import it in app.js.
Show answer
// greet.js
export default function greet(name) {
return `Hello, ${name}!`;
}
// app.js
import greet from "./greet.js";
console.log(greet("Sumi"));
Exercise 2. Import addTax from mathutils.mjs under the name withVat.
Show answer
import { addTax as withVat } from "./mathutils.mjs";
console.log(withVat(200)); // 230
Frequently Asked Questions
Should I use named or default exports?
Named exports make it clear what each file offers and help editors auto-complete and rename. Many teams use named exports everywhere and default exports only for a file’s single main item, such as a React component.
Can I load a module only when it is needed?
Yes. await import("./chart.js") loads a module on demand and returns a promise. This is called a dynamic import, and it helps pages load faster.
Summary
exportshares values;importbrings them into another file.- Named imports use braces; the default import does not.
- Browsers need
<script type="module">and a web server. - Modules have private scope, strict mode and run only once.
Next: Project: Build a Quiz App.
