Lesson 5 of 12 · 11 min · Core language
ES modules: import, export and project structure
What you will learn
- Why modules exist and what each one gets: its own scope
- Named and default
exportand the matchingimportforms - Dynamic
import()for lazy loading - Use modules in the browser (
type="module") and in Node.js - Compare ES modules with CommonJS and avoid circular imports
In simple words
A big program in one file is like a thousand-page book with no chapters. Modules let you split code into files, each with a clear job, where each file decides what it shares with the others and keeps everything else private. You then import only what you need, which also lets build tools remove code you never use.
Words to know
- Module: a file of JavaScript with its own scope that can export and import values.
- Export: making a value available to other modules.
- Import: bringing a value from another module.
- Bundler: a tool such as Vite that combines modules into files for the browser.
Why modules
Before modules, scripts shared one global scope: names collided, load order mattered and dependencies were implicit. ES modules (ESM), standardised in ES2015, give each file:
- its own scope (top-level variables are not global),
- explicit dependencies (
import), - strict mode automatically,
- static structure so tools can analyse imports and remove unused code (tree shaking).
Named exports
// money.js
export const GST_RATE = 0.18;
export function withGst(price) {
return price * (1 + GST_RATE);
}
export function formatInr(amount) {
return new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(amount);
}
const secret = "not exported"; // private to the module
// app.js
import { withGst, formatInr } from "./money.js";
import { GST_RATE as rate } from "./money.js"; // rename on import
import * as money from "./money.js"; // everything as a namespace object
console.log(formatInr(withGst(1000))); // ₹1,180.00
console.log(money.GST_RATE);
Names in { } must match the export names. You can also export at the end: export { withGst, formatInr };, and rename: export { withGst as addGst };.
Default exports
A module may have one default export:
// Cart.js
export default class Cart {
items = [];
add(item) { this.items.push(item); }
}
// elsewhere: you choose the name
import Cart from "./Cart.js";
import ShoppingCart from "./Cart.js"; // same thing, different local name
import Cart, { MAX_ITEMS } from "./Cart.js"; // default and named together
Named vs default: named exports are explicit, refactor-friendly (rename in one place with tools), easy to auto-import and support several exports per file, so many style guides prefer them. Default exports are common for one main thing per file (React components, pages), and required by some tools (for example lazy-loaded routes).
Important behaviours
- Live bindings: an import is a read-only view of the exporter's variable. If the exporting module changes its
letvariable, importers see the new value. You cannot reassign an import (count = 5is an error); you can call an exported function that changes it. - Modules run once: the first import executes the module, and every later import shares the same instance (a singleton). A module-level
const cache = new Map()is shared by all importers. - Static imports are hoisted:
importstatements must be at the top level (not insideifor functions) and run before the module body. - Top-level
awaitworks in modules:const config = await (await fetch("/config.json")).json();. - File extensions and paths: in browsers and Node.js you write the full path with extension (
./money.js); bundlers often let you omit it. A bare name (import dayjs from "dayjs") refers to a package (resolved by Node.js or the bundler, or an import map in browsers). - JSON and CSS modules:
import data from "./data.json" with { type: "json" };(import attributes) works in modern runtimes; bundlers support more.
Dynamic import
import() loads a module on demand and returns a promise. It is how you do code splitting: do not load heavy code until it is needed.
button.addEventListener("click", async () => {
const { renderChart } = await import("./chart.js"); // downloaded only on first click
renderChart(data);
});
const lang = navigator.language.startsWith("hi") ? "hi" : "en";
const messages = (await import(`./i18n/${lang}.js`)).default;
Frameworks use it for lazy routes and components: const Report = React.lazy(() => import("./Report.jsx"));. Bundlers create separate files ("chunks") for each dynamic import, which improves the first load time and web vitals.
ES modules in the browser
<script type="module" src="/main.js"></script>
- Module scripts are deferred by default and run after the document is parsed.
- Each module is loaded once, with its dependency graph fetched in parallel.
- They are fetched with CORS (cross-origin modules need the right headers), always in strict mode, and
thisat the top level isundefined. - For production, a bundler (Vite, esbuild, webpack, Rollup) combines and minifies modules, handles
node_modulespackages and creates chunks. During development, Vite serves modules directly with fast reloads. import.meta.urlgives the module's URL;import.meta.envis provided by Vite for environment variables.- Import maps (
<script type="importmap">) map bare names to URLs without a bundler.
ES modules in Node.js
Node.js supports ESM natively. Turn it on by either naming files .mjs or adding "type": "module" to package.json:
{ "name": "shop-api", "type": "module", "scripts": { "start": "node server.js" } }
import express from "express";
import { readFile } from "node:fs/promises"; // built-ins use the node: prefix
import { fileURLToPath } from "node:url";
const __dirname = import.meta.dirname; // Node 20.11+ (older: fileURLToPath(import.meta.url))
CommonJS versus ES modules
Older Node.js code uses CommonJS (CJS):
const express = require("express"); // synchronous, dynamic
module.exports = { withGst };
| CommonJS | ES modules | |
|---|---|---|
| Syntax | require(), module.exports |
import, export |
| Loading | synchronous, at run time | static analysis, asynchronous loading |
| Tree shaking | poor | good |
__dirname, __filename |
available | use import.meta.dirname and import.meta.filename |
Top-level await |
no | yes |
| Where | older Node.js and packages | browsers, modern Node.js, bundlers |
Modern Node.js versions can require() ES modules in many cases and import CommonJS packages (with a default export), which has eased the old interoperability problems; check the Node.js documentation for the version you use. New projects should use ESM.
Circular imports
If a.js imports b.js and b.js imports a.js, you get a cycle. Because of live bindings it may work, but if a module uses an imported value before the other module has finished evaluating, you get undefined or a ReferenceError. Fix by moving shared code to a third module, or by importing inside the function that needs it. Tools such as madge or ESLint's import/no-cycle find cycles.
Project structure tips
- One responsibility per module; keep files small enough to understand.
- Group by feature (
orders/,auth/) rather than by type when the app grows. - Do not export mutable state and have others rely on side effects; export functions.
- Keep side effects out of module top level where you can (importing a module should not start a server or fire a request).
- Prefer named exports, relative paths with extensions, and consistent naming.
Common mistakes
- Forgetting
type="module"(Cannot use import statement outside a module). - Omitting the file extension in browsers and Node.js.
- Mixing
requireandimportin one file. - Circular imports and expecting initialisation order to work.
- Importing a default with the wrong syntax (
import { Cart }for a default export). - Huge barrels and importing a whole library for one function.
Try it yourself
- Split a script into
money.js,cart.jsandapp.jswith named exports, and load it with<script type="module">(serve it with a local server such asnpx serve; modules do not load fromfile://). - Add a default export and import it with a different name.
- Use
import()to load a module only when a button is clicked and watch the Network tab. - Create a Node.js project with
"type": "module"and import a built-in with thenode:prefix. - Create a circular import on purpose, see the error, and fix it.
Check yourself
What is the difference between a named and a default export?
A module can have many named exports, imported by exact name in braces; it can have one default export, imported with any local name without braces.
Why must you use a local server to try ES modules in the browser?
Module scripts are fetched with CORS, which browsers do not allow for file:// URLs; a local HTTP server solves it.
What does dynamic import() return and what is it used for?
A promise for the module; it loads code on demand, enabling lazy loading and code splitting.
How do you enable ES modules in a Node.js project?
Set "type": "module" in package.json (or use the .mjs extension), then use import and export.
Interview questions
What are the advantages of ES modules over global scripts?
Each file has its own scope, dependencies are explicit, loading and ordering are managed by the platform, strict mode is the default, and static analysis enables tree shaking and better tooling.
What are live bindings?
Imports are read-only references to the exporting module's variables, so they reflect later changes made by the exporter, unlike CommonJS, which copies the exported value.
What is tree shaking?
Removing unused exports from the final bundle, possible because ES module imports and exports are static and can be analysed at build time.
Summary
- Modules give each file its own scope and explicit
importandexport. - Use named exports by default; one default export per module where tools expect it.
import()loads code on demand;type="module"in browsers,"type": "module"in Node.js.- Prefer ESM to CommonJS; avoid circular imports and top-level side effects.
Going deeper
- MDN: JavaScript modules: the complete guide.
- MDN: import and export: syntax reference.
- Node.js: ECMAScript modules: ESM in Node.js and interoperability with CommonJS.
- ECMAScript specification: modules: the formal rules.
See how much of this you can explain
A free mock interview asks you new questions on JavaScript from fundamentals to async for Frontend Developer and scores every answer, with what to fix.