Topic 13 / 15

Modules — import & export

~8 min read  //  JavaScript Series  //  Coding India

Why Modules

One giant script file means global name collisions and no reuse. ES modules give every file its own scope — you explicitly export what others may use and import what you need.

Named Exports

// utils.js
export const TAX_RATE = 0.18;

export function withTax(amount) {
  return amount * (1 + TAX_RATE);
}

export function formatINR(n) {
  return new Intl.NumberFormat("en-IN",
    { style: "currency", currency: "INR" }).format(n);
}
// app.js
import { withTax, formatINR } from "./utils.js";

console.log(formatINR(withTax(199)));

// rename on import
import { withTax as addTax } from "./utils.js";

Default Exports

One main thing per file — imported with any name, no braces:

// api.js
export default async function api(path) { ... }
import api from "./api.js";

Style guidance: named exports are easier to refactor and autocomplete; many teams use them exclusively. Mixing both in a file is fine (React does: export default Component plus named helpers).

Modules in the Browser

<script type="module" src="app.js"></script>

type="module" changes the rules: imports work, strict mode is automatic, the script is deferred until HTML is parsed, and top-level await is allowed. Module files must be served over HTTP — use a dev server (npx serve or Vite), not file://.

Module Scope & Singletons

A module’s code runs once, no matter how many files import it. Module-level state is therefore shared — an easy way to make a singleton:

// store.js
const state = { user: null };
export function setUser(u) { state.user = u; }
export function getUser() { return state.user; }

Dynamic Import

Load code on demand — the basis of route-level code splitting:

button.addEventListener("click", async () => {
  const { renderChart } = await import("./charts.js");  // fetched only now
  renderChart(data);
});

npm Packages

npm init -y
npm install dayjs
import dayjs from "dayjs";     // bundlers/Vite resolve from node_modules
dayjs().format("DD MMM YYYY");

With a tool like Vite (which you’ll meet in the React series), npm imports, hot reload, and production bundling all work out of the box.