Web Development · Module 8 · Lesson 11 min read

ES Modules

Splitting code into files

Modules let each file export what others need, and keep everything else private.

JavaScript
// math.js
export const PI = 3.14159;
export function area(r) { return PI * r * r; }
export default function greet() { return "hi"; }

// main.js
import greet, { area, PI } from "./math.js";
import * as math from "./math.js";
  • Named exports: many per file, imported with { }.
  • Default export: one per file, imported with any name.

In the browser

HTML
<script type="module" src="main.js"></script>

Module scripts are deferred automatically, run in strict mode, have their own scope (no accidental globals), and need a server (they don't work from file://).

Dynamic import: load code only when needed

JavaScript
const { Chart } = await import("./chart.js");

This makes the first page load smaller (code splitting).

CommonJS vs ES modules

Older Node.js code uses require() / module.exports (CommonJS). Modern code uses import / export. In Node, set "type": "module" in package.json to use ES modules.

Example

JavaScript
// ── utils.js ──
export const formatPrice = (n) => `Rs ${n.toFixed(2)}`;
export function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
export default class Cart {
  items = [];
  add(price) { this.items.push(price); return this; }
  total() { return sum(...this.items); }
}

// ── main.js ──
import Cart, { formatPrice } from "./utils.js";

const cart = new Cart().add(120).add(80.5);
console.log(formatPrice(cart.total()));   // Rs 200.50

// ── index.html ──
// <script type="module" src="main.js"></script>
// 💻 Needs several files and a local server (e.g. Vite) — try it on a computer