Skip to content
FrontDepth, Home

JavaScript Deep Dive

ES modules

How JavaScript files depend on each other: import and export forms, module scope, static structure and tree shaking, live bindings, evaluation order and cycles, dynamic import and top-level await, CommonJS interop, bundlers and Vite.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

Before you start

No prerequisites.

This topic starts at Junior level.

JuniorConcept

What an ES module is

An ES module is a JavaScript file that declares what it needs with import and what it offers with export. Before modules were standardized (ES2015), every <script> shared one global : each top-level var and function became a global, and the order of script tags had to be managed by hand. Modules fix this:

  • Own scope. Top-level variables of a module are local to it. Nothing reaches window unless you put it there.
  • Strict mode, always. No "use strict" is needed, and top-level this is undefined.
  • Evaluated once. However many files import a module, its code runs once, and every importer shares that one instance.
  • Explicit dependencies. Each file names what it uses, so browsers and tools can build the dependency graph without running code.
JavaScript
// math.js
export const PI = 3.14159;
export function area(radius) {
  return PI * radius * radius;
}
JavaScript
// main.js
import { area } from "./math.js";
console.log(area(2)); // 12.56636

In the browser

HTML
<script type="module" src="/main.js"></script>
  • Module scripts are deferred by default: they download in parallel with HTML parsing and run after parsing, in document order. With async, a module runs as soon as it and its imports have loaded, in no particular order.
  • Modules are fetched with CORS. Opening index.html from file:// therefore fails; use a local server. The server must send a JavaScript MIME type such as text/javascript.
  • A module that several <script> tags or imports refer to still runs only once.

In Node.js

A file is an ES module if it ends in .mjs, or ends in .js and the nearest package.json has "type": "module". .cjs files are always CommonJS. Without a "type" field, Node.js (since 22.7 and 20.19) also detects import/export syntax in a .js file, but its docs recommend setting the field explicitly, because detection has a performance cost. The senior sections compare the two systems.

JuniorExample

The forms of import and export

JavaScript
// user.js
export const ROLES = ["admin", "editor"];

export function formatName(user) {
  return user.first + " " + user.last;
}

export default class User {}
JavaScript
// app.js
import User, { ROLES, formatName as fullName } from "./user.js";
import * as users from "./user.js";
import "./polyfills.js";

Named exports

export const, export function, export class or a list: export { a, b as c }. The importer uses the exact name in braces and may rename it with as. A misspelled name fails before any code runs, with an error such as SyntaxError: The requested module './user.js' does not provide an export named 'formatNme'.

Default export

At most one per module: export default expression. The importer chooses any name (User above). Combined form: import User, { ROLES } from "./user.js".

Namespace import

import * as users gives one object with every export as a property: users.ROLES, users.formatName, and the default export as users.default. The object is read-only.

Side-effect import

import "./polyfills.js" runs the module without importing any name. Typical for polyfills and global CSS in bundled apps.

Re-exports

JavaScript
// index.js
export { formatName } from "./user.js";
export { default as User } from "./user.js";
export * from "./dates.js";
export * as validators from "./validators.js";

export * re-exports all named exports, but not the default export. A file made only of such re-exports is called a barrel.

Named or default?

Many teams prefer named exports: the same name everywhere in the codebase, better autocomplete and renaming, and typos caught at link time. Default exports remain common where a tool expects them: React.lazy expects a module whose default is a component, and some frameworks expect a default export per route file.

Specifiers

In browsers, a relative specifier needs ./ or ../ and the file extension: "./user" is not resolved to user.js. A bare specifier such as "react" needs an import map or a bundler (see the senior sections).

MiddleConcept

Static structure and tree shaking

import and export declarations are static:

  • they are allowed only at the top level of a module, not inside if blocks or functions;
  • the specifier is a string literal, never a computed value;
  • imports are hoisted: a module's dependencies are loaded and linked before any of its own code runs.

Because of this, the whole module graph is known before execution. Loading a graph has three phases:

  1. Construction: fetch and parse each module, read its import declarations, and repeat for every dependency.
  2. Linking: create the bindings for every export and connect each import to the export it names. A missing export fails here, before any code has run.
  3. Evaluation: run the module bodies, dependencies first.

Tree shaking

Since a bundler (Rollup, Rolldown, webpack, esbuild) can see statically which exports are used, it can drop the ones nobody imports:

JavaScript
// format.js
export function formatPrice(value) {
  return value.toFixed(2) + " AZN";
}

export function formatHugeReport(rows) {
  return rows.map((row) => row.join(";")).join("\n");
}
JavaScript
// cart.js
import { formatPrice } from "./format.js";

If nothing else imports formatHugeReport, the production bundle does not contain it.

What prevents it

  • Top-level side effects. A module that does something when evaluated (patches a prototype, registers a global, writes to storage) must be kept even if no export is used. The "sideEffects" field in package.json, introduced by webpack and read by most bundlers, tells them which files are safe to drop: false for none, or a list such as ["*.css"].
  • CommonJS. require() is an ordinary function call and module.exports an object built at runtime, so a bundler cannot generally prove that a property is unused.
  • Dynamic access to a namespace. utils.formatPrice is analysable; utils[name] forces the bundler to keep every export.
  • Code with hidden effects. A top-level call such as const theme = createTheme() is kept unless the bundler can prove it is pure; some bundlers accept a /* @__PURE__ */ annotation in front of the call.

Barrel files are not a problem for tree shaking in production builds, but they make development servers and test runners load every module behind the barrel, and they make circular imports easier to create.

MiddleConcept

Live bindings: imports are views, not copies

An imported name is not a copy of the exported value. It is a live, read-only view of the exporting module's variable.

JavaScript
// counter.js
export let count = 0;

export function increment() {
  count += 1;
}
JavaScript
// main.js
import { count, increment } from "./counter.js";

console.log(count); // 0
increment();
console.log(count); // 1

main.js never assigned count, yet it sees 1: both names refer to the same binding in counter.js.

Read-only for importers

Writing count = 5 in main.js throws TypeError: Assignment to constant variable. at runtime. Only the exporting module can assign its variables; to change them from outside, export a function such as increment. Properties of an exported object can still be changed by any importer (settings.debug = true), which is shared mutable state across the whole app, so do it deliberately.

The default export is a special case

export default expression evaluates the expression once and exports that value. export { value as default } exports the binding. If the exporter later reassigns value, only the second form shows the change (MDN describes exactly this difference).

Why it matters

  • Cycles. A binding that is not initialized yet when a module starts can become valid later. Without live bindings, circular imports would see undefined forever.
  • Comparison with CommonJS. const { count } = require("./counter") copies the value at the moment of the call; later changes are invisible.
  • Bundlers must reproduce it. webpack keeps imports live by defining each export as a getter on the module's exports object, so every read returns the current value. Rollup and Rolldown use scope hoisting instead: modules are concatenated into one scope, so an import becomes a direct reference to the same variable.

A namespace object (import * as counter) is live as well: counter.count always reads the current value.

MiddlePitfalls

Evaluation order and circular imports

Evaluation goes depth-first: before a module's body runs, all the modules it imports are evaluated, in the order its import declarations appear. A module that was already evaluated is skipped, so a shared dependency runs once, before the first module that needs it. The entry module runs last.

This is why import order can matter: if main.js imports ./polyfills.js first and ./app.js second, the polyfills run before any code of app.js. Relying on that is fragile, though; a module should import what it needs itself.

Circular imports

If a.js imports b.js and b.js imports a.js, both cannot run first. When the graph is entered at a.js, the loader starts evaluating b.js first. Its import of a.js points to a module that is already in progress, so b.js runs while a.js has not run yet:

JavaScript
// a.js
import { b } from "./b.js";
export const a = "a";
console.log("a sees " + b);
JavaScript
// b.js
import { a } from "./a.js";
export const b = "b";
console.log("b sees " + a);

Running a.js throws ReferenceError: Cannot access 'a' before initialization from b.js. The binding a already exists (it was created during linking), but its const declaration has not executed, so it is still in the . With var you would get undefined instead, which is a quieter version of the same bug.

What works inside a cycle

  • Function declarations are initialized during linking, so b.js may call a function exported by a.js at its top level, as long as that function does not read a.js's uninitialized let/const variables.
  • Reading imports later, inside functions that run after the whole graph has been evaluated, works because live bindings then point to initialized values.

How to fix and prevent cycles

  • Move the shared code into a third module that both import.
  • Read imports inside functions rather than at module top level.
  • Watch barrel files: a component that imports from "../components" (whose index.js re-exports that same component) creates a cycle through the barrel.
  • Detect cycles automatically, for example with the import/no-cycle rule of eslint-plugin-import or with madge --circular.
MiddleWeb platform

Dynamic import() and top-level await

import()

import(specifier) is an expression, not a declaration. It can appear anywhere (in functions, in if blocks, even in classic scripts), its specifier may be computed, and it returns a promise for the module namespace object:

JavaScript
button.addEventListener("click", async () => {
  const { openEditor } = await import("./editor.js");
  openEditor();
});

A module that is already loaded is not evaluated again: import() resolves to the same namespace object every time.

Code splitting

Bundlers treat every import() as a split point: editor.js and the dependencies only it uses go into a separate chunk, which the browser downloads the first time the code runs. Static imports keep code in the initial bundle; dynamic ones move it out.

JSX
const Settings = lazy(() => import("./Settings.jsx"));

React.lazy needs a promise that resolves to an object whose default is a component. For a named export, map it: lazy(() => import("./Chart.jsx").then((m) => ({ default: m.Chart }))).

A bundler can split only what it can analyse. A fully dynamic import(url) is left to the browser at runtime; Vite and webpack accept a template with a fixed folder and extension, such as import(`./locales/${lang}.js`), and create one chunk per matching file.

Top-level await

In a module, await may appear at the top level:

JavaScript
// config.js
const response = await fetch("/config.json");
export const config = await response.json();

The module becomes asynchronous: every module that imports it, directly or through other modules, waits until it has finished before its own body runs. Modules that do not depend on it keep evaluating in the meantime (MDN: it does not block sibling modules).

Consequences:

  • A slow top-level await in the entry chain delays the start of the whole app. For data that is not needed to start, export a promise or a loader function instead.
  • If it rejects, the module fails to evaluate, its importers fail too, and every later import of that module receives the same error.
  • It is available only in ES modules: Chrome 89+, Firefox 89+, Node.js 14.8+. Safari added it in Safari 15, but MDN counts support as partial until Safari 27: several modules importing the same module with top-level await at once is not handled. A CommonJS require() of a graph that contains top-level await throws ERR_REQUIRE_ASYNC_MODULE.
SeniorWeb platform

ES modules and CommonJS in Node.js

CommonJS (require, module.exports) was Node.js's module system long before ES modules existed, and most of npm was written in it. The two systems differ in more than syntax:

CommonJSES modules
Loadingsynchronous, when require() runsgraph parsed and linked first, then evaluated (possibly asynchronously)
Imported valuesread from the module.exports object; destructuring copieslive bindings
Top-level awaitnoyes
Paths of the current file__filename, __dirnameimport.meta.filename, import.meta.dirname
File types.cjs, or .js with "type": "commonjs".mjs, or .js with "type": "module"

Importing CommonJS from ES modules

import legacy from "./legacy.cjs" gives module.exports as the default export. Named imports such as import { parse } from "./legacy.cjs" work when Node.js's static analysis of the source can detect them. The detection is a best-effort heuristic, and such named imports are not live.

require() of ES modules

require() can load ES modules without a flag since Node.js 20.19, 22.12 and 23.0, and Node.js 25.4 removed the feature's experimental status. It returns the module namespace object:

JavaScript
const { formatDate } = require("./dates.mjs");
const Logger = require("./logger.mjs").default;

A module can choose what require() returns by exporting a value under the string name "module.exports": export { Logger as "module.exports" }. The one hard limit: the required graph must be synchronous. If any module in it uses top-level await, Node.js throws ERR_REQUIRE_ASYNC_MODULE; use import() there.

This lets CommonJS code use ESM-only packages, which used to push library authors into shipping two builds.

The dual package hazard

A package that ships both a CommonJS and an ESM build can end up loaded twice in one app: once through require, once through import. That means two module instances: two caches, two copies of singleton state, and instanceof checks failing between them. The package's exports field decides which file each loader receives:

JSON
{
  "name": "date-kit",
  "type": "module",
  "exports": {
    ".": {
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    }
  }
}

Keep state outside the duplicated files, or ship only ESM and let require(esm) serve CommonJS consumers.

SeniorFramework

Bare specifiers, bundlers and the Vite dev server

Browsers resolve only URLs: "./utils.js", "/src/app.js", "https://…". A bare specifier such as "react" is an error, unless something maps it to a URL.

Import maps

HTML
<script type="importmap">
  {
    "imports": {
      "react": "/vendor/react.js"
    }
  }
</script>
<script type="module" src="/main.js"></script>

Import maps have been available in all major browsers since March 2023 (Baseline widely available). The map must come before the module scripts that rely on it. They make no-build setups practical, but they do not remove the request waterfall: each nested import is discovered only after its parent has been downloaded and parsed. <link rel="modulepreload"> lets you announce known modules early.

What a bundler does

A bundler parses every file to find its imports, follows them into a module graph, rewrites each module into a function and adds a small runtime that calls those functions in dependency order. The platform's Mini Bundler build project lets you write one yourself, from parsing imports with acorn to handling cycles. The output of a classic bundler, simplified, has this shape:

JavaScript
const modules = {
  "./math.js": (exports) => {
    exports.area = (radius) => 3.14159 * radius * radius;
  },
  "./main.js": (exports, require) => {
    const { area } = require("./math.js");
    console.log(area(2));
  },
};

const cache = {};
function require(id) {
  if (cache[id]) return cache[id];
  const exports = (cache[id] = {});
  modules[id](exports, require);
  return exports;
}

require("./main.js");

Because of the cache, every module runs once, however many modules require it. Real bundlers add tree shaking, scope hoisting, chunks at every import() and minification.

Vite in development

Vite does not bundle your source code in development. The browser loads /src/main.jsx as a native module, and each import becomes a request to the dev server, which transforms that one file on demand (JSX, TypeScript) through its plugin pipeline. Import analysis rewrites bare imports to real URLs, such as /node_modules/.vite/deps/react.js?v=…. Dependencies are pre-bundled once with Rolldown (Vite 8): CommonJS packages become ESM, and a package with hundreds of internal modules (lodash-es has over 600) becomes one request. HMR runs over the same native modules: after an edit the browser imports the changed module again, and code that called import.meta.hot.accept() swaps it in place without a page reload.

The platform's tour "Vite: from request to module" (vite v8.3.8) follows this path through the transform middleware, the plugin container, import analysis and HMR. For production, vite build still bundles, because many small nested requests are slower than a few optimized chunks.

SeniorInterview tips

Interview tips

A 30-second answer. "ES modules are files with their own scope that declare dependencies with import and their API with export. The structure is static, so the whole graph is known before any code runs: tools can tree-shake it, and the loader links every import to its export. Imports are live read-only bindings, each module is evaluated once, and import() loads code on demand."

Questions you are likely to get

  • Named or default export? Say what you prefer and why (stable names, refactoring), and where a default export is expected (React.lazy, route files).
  • What is tree shaking and when does it fail? Static imports make unused exports visible. It fails with side effects at top level, CommonJS and dynamic namespace access; "sideEffects" tells the bundler what it may drop.
  • What is a live binding? Show the counter example, then the read-only TypeError, then the difference between export default value and export { value as default }.
  • We get "Cannot access 'x' before initialization" at startup. A circular import evaluated a module before its dependency's const declarations ran. Explain the evaluation order and how to break the cycle.
  • How does code splitting work? Each import() is a split point; the chunk is fetched when the code runs.
  • ESM vs CommonJS. Loading model, live bindings, top-level await, interop in both directions, require(esm) and ERR_REQUIRE_ASYNC_MODULE.

Mistakes that cost points

  • Saying an import copies the value. It is a live binding; only CommonJS destructuring copies.
  • Saying modules are evaluated each time they are imported. Once per module instance; later imports reuse it.
  • Saying type="module" scripts block parsing. They are deferred by default.
  • Calling import() synchronous. It returns a promise.

Senior signal

Connect the language rules to the tools: how a bundler builds the graph and rewrites modules, why Vite serves native ESM in development but bundles for production, how top-level await changes startup, and how you would find and break an import cycle in a large codebase.

JuniorReview checklist

What to check when reviewing ES modules

Use this list when you review code you did not write: a teammate's pull request, a snippet from a library's issue tracker or a suggestion from an AI assistant. One careless import can crash the app at startup, bloat the initial bundle or defeat tree shaking (dropping unused exports).

  • Does a new import close a cycle? If two files import each other, even through a barrel index.js, one runs before the other's const declarations have run and throws ReferenceError: Cannot access 'a' before initialization. Run madge --circular or the import/no-cycle lint rule.
  • Does the module do work at the top level? Code that patches a prototype, registers a global or writes to storage runs on import and stays in the bundle even if nothing is used. Prefer an exported function; in a library, check "sideEffects" in package.json.
  • Is code that the first screen does not need imported statically? Load code used only after a click with import(), which puts it in a separate chunk; for React.lazy, the default export must be a component.
  • Is there a top-level await on the startup path? Every module that depends on it waits, and fails if it rejects. For data not needed at start, export a promise or a loader function.
  • Does an importer write to an imported name or an exported object? count = 5 throws a TypeError, since imports are read-only live bindings, and mutating an exported object creates app-wide shared state. Prefer exporting a function such as increment.
  • Will the specifiers resolve where the code runs? Browsers need ./ and the extension in relative paths, and an import map or a bundler for bare names like "react". In Node.js, check .mjs or "type": "module".

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    4 predict-output · 3 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    6 questions

Hands-on work that uses this topic.

Build Your Own X

Guided tours through the source of real libraries that rely on it.