ES Modules in JavaScript: import, export, Default vs Named Exports, Re-exports and Live Bindings
The standard JavaScript module syntax in depth: named and default exports, every form of import, renaming, namespace imports, side-effect imports, re-exports and barrel files, live read-only bindings, hoisting, strict mode, evaluation order, circular imports, and default-vs-named best practices.
kvi5hnuCode Sprout team member9 min readOn this page
ES2015 gave JavaScript its own module system, usually called ES modules (ESM). The idea is the same as CommonJS (article 74): each file is a module with a private scope that exports some values and imports others. But it's part of the language itself, it works in browsers and Node, and its imports and exports are static: they're written as declarations that tools can read without running any code. That one design choice enables tree shaking, early error checking, editor auto-imports and efficient loading.
The examples here show several files. Module syntax can't run in a single snippet, so each output was produced by running the files with Node.
Exporting
Named exports
Put export in front of any top-level declaration:
// file: geometry.js
export const PI = Math.PI;
export function circleArea(r) {
return PI * r * r;
}
export class Rectangle {
constructor(w, h) { this.w = w; this.h = h; }
area() { return this.w * this.h; }
}
function round2(n) { // not exported: private to this file
return Math.round(n * 100) / 100;
}
Or declare things normally and list the exports in one place, often at the end, optionally renaming with as:
// file: geometry.js
const PI = Math.PI;
function circleArea(r) { return PI * r * r; }
function round2(n) { return Math.round(n * 100) / 100; }
export { PI, circleArea, round2 as roundToCents };
The braces in export { ... } are not an object literal; they're a list of names. export { Math.sin as sin } is a syntax error, because only identifiers can go there.
Default exports
A module can also have one default export, typically its main function or class:
// file: logger.js
export default class Logger {
log(message) { console.log(`[log] ${message}`); }
}
Unlike named exports, export default takes any expression, so it can export anonymous functions, classes, objects or computed values:
// file: settings.js
export default { theme: "dark", pageSize: 20 }; // these braces ARE an object
export default const x = 1; is a syntax error (a declaration isn't an expression); write const x = 1; export default x;. A module can mix one default export with any number of named exports, though most modules pick one style.
Importing
// file: main.js
import Logger from "./logger.js"; // default export, any local name
import { PI, circleArea } from "./geometry.js"; // named exports, exact names
import { roundToCents as round } from "./geometry.js"; // rename on import
import * as geometry from "./geometry.js"; // namespace object
import Logger2, { PI as pi } from "./mixed.js"; // default + named together
import { default as Settings } from "./settings.js"; // default by its real name
import "./polyfills.js"; // run for side effects only
console.log(circleArea(1).toFixed(2), geometry.PI === PI); // 3.14 true
- Named imports must match an exported name; a typo is a SyntaxError reported before any code runs:
The requested module './geometry.js' does not provide an export named 'cirleArea'. - Default imports choose their own local name. That's convenient, but it means the same thing may be called different names in different files.
- Namespace imports (
import * as geometry) give an object whose properties are the module's named exports (plusdefault, if any). Its keys are sorted, it hasSymbol.toStringTagof"Module", and its properties can't be assigned or deleted. - Side-effect imports (
import "./polyfills.js") run a module without importing anything: useful for polyfills, global CSS in bundlers, or registering custom elements.
Module specifiers
The string after from must be a plain string literal (not a variable or template literal), because it's read before the code runs:
"./utils.js","../lib/math.js": relative to this module's URL or file. In browsers and Node's ESM, the file extension is required."/js/app.js"or"https://cdn.example.com/lib.js": absolute paths or full URLs (browsers)."node:fs": Node built-ins."lodash-es": bare specifiers, resolved by Node fromnode_modules, by bundlers, or in browsers by an import map (article 76).
Imports are hoisted and top-level only
Import declarations are processed before the module's code runs, so imported names are usable anywhere in the module, even above the import line (convention still puts imports at the top). And import / export declarations may only appear at the top level of a module, never inside a function, if block or loop:
if (user.isAdmin) {
import { adminTools } from "./admin.js"; // SyntaxError
}
For conditional or on-demand loading, use dynamic import() (article 76).
Live bindings
This is the biggest semantic difference from CommonJS. An import is not a copy of a value; it's a live, read-only view of the exporting module's variable:
// file: counter.js
export let count = 0;
export function increment() { count++; }
// file: main.js
import { count, increment } from "./counter.js";
console.log(count); // 0
increment();
increment();
console.log(count); // 2: sees the exporter's current value
count = 10; // TypeError: Assignment to constant variable.

- Imports behave like
constin the importing module: assigning to one throws aTypeError. Only the module that owns a variable can change it, which keeps data flow clear. - Imported objects can still be mutated (
settings.theme = "light"works and is visible to every importer), since the binding is read-only, not the object. - CommonJS, by contrast, exports values:
module.exports = { count }copies0once.
Bundlers implement live bindings by turning each export into a getter. This runnable sketch shows the idea:
// the "module": a private variable plus a function that changes it
let count = 0;
const increment = () => { count++; };
// a namespace object with getters, like a bundler generates
const counterModule = Object.freeze({
get count() { return count; },
increment,
});
console.log(counterModule.count);
counterModule.increment();
console.log(counterModule.count);
const copied = { count }; // CommonJS-style copy
console.log(copied.count);
0
1
1
One subtlety: export default with an expression exports the value at that moment, not a live binding:
// file: value.js
let level = 1;
export { level }; // live
export default level; // the value 1, evaluated once
level = 99;
// file: main.js
import levelDefault, { level } from "./value.js";
console.log(levelDefault, level); // 1 99
(export default function f() {} and export { level as default } do create live bindings, since they export a binding rather than evaluate an expression.)
Re-exports and barrel files
A module can pass along exports from other modules without importing them for its own use:
// file: stats/index.js
export { mean } from "./mean.js"; // one named export
export { default as median } from "./median.js"; // someone's default, as a named export
export * from "./spread.js"; // all named exports (not default!)
export * as format from "./format.js"; // a namespace as one named export
export { mean as average } from "./mean.js"; // with renaming
Consumers can then write import { mean, median, format } from "./stats/index.js";. A file whose only job is re-exporting a folder's contents is called a barrel.
Things to know:
export *re-exports named exports only, never the default.- If two
export *sources export the same name, that name is ambiguous: it's silently left out of the namespace, and importing it by name is a SyntaxError (contains conflicting star exports for name ...). Explicitexport { x } fromwins overexport *. - Big barrels can slow down development tools and tests, because importing one function from the barrel loads every module it re-exports. Many teams import directly from specific files in large codebases.
How modules are loaded and run
Because imports are static, the engine builds the module graph before running anything:
- Parse the entry module, find its
importdeclarations, fetch those modules, parse them, and so on recursively. - Link: connect every import to the matching export binding. Missing exports fail here, before any code runs.
- Evaluate: run each module's code once, dependencies first (depth-first, in import order), then the importer.
Each module is evaluated only once per page or process, no matter how many modules import it; they all share the same instance, just like CommonJS's cache.
Module code also differs from classic scripts:
- It's always strict mode (no
"use strict"needed). - Top-level
thisisundefined. - Top-level variables are local to the module, not properties of the global object.
require,module,exports,__dirnameand__filenamedon't exist (Node offersimport.meta.dirnameandimport.meta.filenameinstead).- Top-level
awaitis allowed (article 76).
Circular imports
Cycles are allowed. Because bindings are live, a module in a cycle can use another's exports once they've been initialized; reading one too early hits the temporal dead zone:
// file: a.js
import { bValue } from "./b.js";
export const aValue = "A";
console.log("a sees", bValue);
// file: b.js
import { aValue } from "./a.js";
export const bValue = "B";
console.log("b sees", aValue); // a.js hasn't run yet
Running a.js: b.js is evaluated first (it's a dependency), and reading aValue throws a ReferenceError because a.js's const isn't initialized yet. Function declarations are initialized early, so cycles that only call each other's functions later usually work. As with CommonJS, the best fix is to move shared code into a third module.
Default or named exports?
Both work; many style guides (and large codebases) prefer named exports:
| Named exports | Default export | |
|---|---|---|
| Name at import site | Must match (rename with as) | Anything, so names can drift between files |
| Typos | SyntaxError at link time | Can't happen, but the wrong module still "works" |
| Editor auto-import and refactoring | Excellent | Weaker |
| Several exports per module | Natural | Only one default |
| Common uses | Utilities, constants, most modules | A file's single main class or component; some frameworks require it (e.g. route or page files) |
Common questions
What's the difference between import x from and import { x } from?
Without braces you import the module's default export and name it x. With braces you import the named export called exactly x. Mixing them up is a very common error: if a module has no default export, import x from fails at link time.
Can I import a module conditionally?
Not with import declarations; they must be at the top level. Use const mod = await import("./x.js") inside an if or a function.
Why does changing an imported variable throw?
Imports are read-only live bindings to the exporter's variable. Export a function that changes it (setLevel(n)), so the owning module controls its own state.
Do I need the .js extension in import paths?
In browsers and Node ES modules, yes: specifiers are URLs or exact paths. Bundlers and TypeScript setups often let you omit it, which is why you see extensionless imports in many projects.
Summary
exportbefore a declaration orexport { a, b as c }creates named exports;export default expressioncreates the single default export.import d from,import { a, b as c } from,import * as ns fromandimport "./x.js"cover default, named, namespace and side-effect imports.- Imports and exports are static, top-level and hoisted; missing exports are errors before code runs.
- Imports are live, read-only bindings, unlike CommonJS's copied values;
export default expressionexports a value. export ... fromre-exports;export *skips the default and drops conflicting names.- Modules are strict, have
this === undefinedat the top level, are evaluated once in dependency order, and tolerate cycles if bindings aren't read too early.
Practice Questions
A module has this code and export const version = 2;. Write one import that gets both, naming the function init.
export default function () {}
Answer
import init, { version } from "./module.js";
lib.js contains this code, and another module runs import * as ns from "./lib.js". What are ns.default and ns.a, and what happens with ns.a = 3?
export default 1;
export const a = 2;
Answer
ns.default is 1 and ns.a is 2. Assigning to a namespace property throws a TypeError (modules are strict, and namespace properties are read-only).
Why doesn't this code see an export that utils.js creates inside if (debug) { ... }?
import { helper } from "./utils.js"
Answer
It can't: export is only allowed at a module's top level, so such code is a SyntaxError. A module's exports are fixed and known before it runs.
A barrel file contains snippet A, and both files export format. What does snippet B do?
export * from "./a.js";
export * from "./b.js";
import { format } from "./index.js"
Answer
It fails with a SyntaxError about conflicting star exports. The ambiguous name is excluded; fix it with an explicit export { format } from "./a.js"; in the barrel.
Previous: JavaScript Modules Explained: Why Modules Exist, IIFEs, Closures and CommonJS require

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.