A module is a file that encapsulates part of your code and exposes only what other files need.
Modules make code:
In modern JavaScript, modules are a core part of application structure.
<script type="module" src="./main.js"></script>With type="module":
export const PI = 3.14;
export function add(a, b) { return a + b;}const PI = 3.14;
function add(a, b) { return a + b;}
export { PI, add };const version = "1.0.0";
export { version as appVersion };export default function createApp() { return "app";}Each module can only have one default export.
You can use both named and default exports in the same file:
export const version = "1.0.0";
export default function createApp() { return "app";}import { PI, add } from "./math.js";import createApp from "./app.js";import { appVersion as version } from "./config.js";import * as math from "./math.js";
console.log(math.PI);import createApp, { version } from "./app.js";import "./setup.js";This is useful when a module should run code on load.
export function formatDate(date) { return date.toISOString();}
export function clamp(value, min, max) { return Math.min(Math.max(value, min), max);}export function Button() { return "<button>Click</button>";}export async function fetchUser(id) { const response = await fetch(`/api/users/${id}`); return response.json();}import { fetchUser } from "./services/user.js";
async function main() { const user = await fetchUser(1); console.log(user);}
main();Dynamic import loads modules on demand.
const module = await import("./heavy-module.js");module.run();This is useful for:
ES modules in browsers usually need to be served over HTTP(S), not opened directly as local files.
Module paths must be correct and explicit.
Variables inside a module do not automatically become globals.
A module is evaluated once and then cached.
Circular imports are possible, but they make code harder to reason about and should be minimized.
Use clear file names and export names.
Use dynamic import when a module is large or not always needed.
Modern tools treat ES modules as the standard model and build on top of them for bundling, optimization, and code splitting.
Node.js supports ES modules as well, though CommonJS still exists in many codebases.
ES Modules:
import and exportCommonJS:
require and module.exportsModules are the foundation of maintainable modern JavaScript.
Best practices: