import and exportJavaScript ES modules (ESM) let you split large applications into focused files that explicitly share functions, classes, and constants. Every module runs in its own private scope in strict mode, preventing global variable leaks across files.
JavaScript modules support two complementary export styles:
export const ..., export function ...): A file can have many named exports, imported using matching curly braces import { formatTax, TAX_RATE } from "./tax.js";.export default ...): Each module can have at most one default export, imported without braces under any local name import UserCard from "./UserCard.js";.Named exports are easier to refactor in large teams because IDE rename tools track exact symbol names across every file.
import() ExampleStatic import statements sit at the top of a file for tree-shaking and bundle analysis, while dynamic import() loads heavy features lazily only when needed.
// mathUtils.js (module exports)
export const PI = 3.14159;
export function circleArea(radius) {
return PI * radius * radius;
}
export default function formatUnits(val, unit = "px") {
return `${val}${unit}`;
}
// app.js (module consumer)
// import formatUnits, { circleArea } from "./mathUtils.js";
console.log("Area r=3:", Number(circleArea(3).toFixed(2)));
console.log("Formatted:", formatUnits(24));
// Lazy-loading syntax for heavy optional charts:
// const { renderChart } = await import("./charts.js");
type="module" in browser HTML: Loading an ES module via <script src="app.js"></script> without type="module" throws SyntaxError: Cannot use import statement outside a module../tax.js rather than ./tax.file:// directly: Browsers block ES module imports over file:// due to CORS rules. Always run a local dev server like Vite or npx serve.require)?ES Modules (import/export) are the official JavaScript standard supported in both browsers and Node.js, enabling static analysis and tree-shaking. CommonJS (require/module.exports) is an older synchronous Node.js-only format.
Yes, use as inside braces: import { format as formatDate } from "./date.js";.
No, <script type="module"> behaves like defer automatically, downloading in parallel and executing only after HTML parsing finishes.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.