ES Modules in JavaScript Import Export and Live Bindings
ES modules share code through import and export, run once, and export live bindings that update when the exporter changes a value. See the forms and rules.

A script that grew past one file needs a way to share code, and for fifteen years JavaScript had none in the language: pages concatenated files and shared globals, and Node.js invented require. ES modules, standardized in ES2015, are the answer built into the language, and they work in browsers, Node.js, Deno and Bun with the same syntax. They look like a new spelling of require, and they are different in ways that matter: the dependency graph is known before any code runs, the exports are live bindings and not copied values, and a module's top level runs once. This post explains the forms, the live binding rule that surprises people from CommonJS, the caching that makes a module a singleton, and the Node.js specifics. The snippets load small modules from data: URLs so each example is self-contained and its output real. The dynamic form is in the post on dynamic import() and top-level await, and the JSON form in the post on import attributes.
The forms
A module exports names and imports them. The statement forms cover everything, and the comments below show the common ones.
// math.js
export const PI = 3.14159;
export function area(radius) {
return PI * radius ** 2;
}
export default class Circle {}
export { area as circleArea };
export * from "./shapes.js";
export * as units from "./units.js";
// app.js
import Circle, { PI, area as calculateArea } from "./math.js";
import * as math from "./math.js";
import "./side-effects.js";
import { default as Shape } from "./math.js";A file can have one default export and any number of named ones. import * as math gives a namespace object holding every export, and import "./file.js" loads a module only for its side effects. The as keyword renames in either direction, and export * from re-exports every named export of another module without importing it into the current scope. The default export is itself a binding called default, and import x from is shorthand for import { default as x } from.
Imports are live bindings
An import is a read-only view of a variable in the exporting module. It is not a copy taken at import time, so when the exporter changes the variable, the importer sees the new value.
const counter = await import(
"data:text/javascript," +
encodeURIComponent(`
export let count = 0;
export const state = { calls: 0 };
export function increment() {
count++;
state.calls++;
}
`)
);
console.log(counter.count, counter.state.calls);
counter.increment();
counter.increment();
console.log(counter.count, counter.state.calls);
try {
counter.count = 100;
} catch (error) {
console.log(error.name + ": " + error.message);
}
const { count } = counter;
counter.increment();
console.log(count, counter.count);
console.log(Object.keys(counter), counter[Symbol.toStringTag]);0 0
2 2
TypeError: Cannot assign to read only property 'count' of object '[object Module]'
2 3
[ 'count', 'increment', 'state' ] ModuleThe importer read count as 0, then as 2 after two calls, with no re-import. Assigning to it through the namespace failed, because the binding belongs to the exporter alone, and only the exporting module can change it. The destructuring on the second last line took a copy at that moment: count stayed at 2 while counter.count moved to 3. That is the one way to lose liveness, and CommonJS behaves like it all the time, since require returns the value that module.exports held when it ran. The namespace object lists the exports in alphabetical order and reports itself as Module.
The practical rule is that mutable state exported from a module is visible and changeable only by that module, so expose it through functions, as the example does, and not by expecting importers to write to it.
Evaluated once and cached
A module's top-level code runs the first time it is imported, and the result is cached by the module's resolved URL. Every later importer gets the same module instance.
const source = "data:text/javascript," + encodeURIComponent(`
console.log("module body runs");
export const id = Math.random();
export const registry = new Map();
`);
const first = await import(source);
const second = await import(source);
console.log(first === second, first.id === second.id);
first.registry.set("a", 1);
console.log(second.registry.get("a"));
const other = await import(source + "#copy");
console.log(other === first);module body runs
true true
1
module body runs
falseThe log line appeared once, and the second import returned the identical namespace object, with the same random number and the same Map. That makes a module a natural singleton: a configuration object, a connection pool or a registry defined at the top level is shared by everything that imports it. A different URL is a different module, which the last line shows with a fragment added to the specifier. Bundlers and tools that load a file by two different paths, through a symlink or a case difference, can create two instances, a source of "why are there two copies of my singleton" bugs.
Hoisting and static structure
import declarations are hoisted to the top, resolved and loaded before any code in the importing module runs, and they cannot appear inside a block or a function. The graph of dependencies is known statically, which allows tools to remove unused exports, check names before running and load files in parallel.
console.log("module body starts");
import { readFileSync } from "node:fs";
console.log(typeof readFileSync);
console.log(typeof this);
console.log(typeof require, typeof module, typeof __dirname);
console.log(typeof import.meta.url, typeof import.meta.dirname, typeof import.meta.filename);
try {
eval("if (true) { import fs from 'node:fs'; }");
} catch (error) {
console.log(error.name);
}module body starts
function
undefined
undefined undefined undefined
string string string
SyntaxErrorThe import sits below the first log line and was still available above it, because imports are hoisted and the module it names was loaded before this file's code ran. Top-level this is undefined, and the CommonJS names require, module and __dirname do not exist. In their place, import.meta.url is the file's URL, and in Node.js 20.11 and later import.meta.dirname and import.meta.filename give the plain paths. An import inside a block is a syntax error. A conditional load needs the function form, import(), which returns a promise.
Circular imports
Two modules that import each other are allowed. The loader evaluates them in an order and the first module to run sees the other's exports before they are initialized. Function declarations work, because they are initialized at the start, and const and class exports are in the temporal dead zone until their line runs, as shown in the post on the temporal dead zone.
The safe patterns are to move shared code into a third module, to read the imported value only inside functions that run later, and to avoid top-level code that uses an import from the cycle. A tool such as madge or ESLint's import/no-cycle finds them.
Choosing named or default exports
A default export lets the importer choose any name, which makes renaming easy and consistent naming hard. Named exports are checked by name on import, so a typo is an error at load time, and editors can autocomplete and rename them across files. We prefer named exports for libraries and utilities, and use a default export where a file is clearly one thing, such as a component or a page. A module that has both a default and named exports forces importers to learn which is which.
const mod = await import(
"data:text/javascript," +
encodeURIComponent(`
export const helper = () => "named";
export default function main() { return "default"; }
`)
);
console.log(mod.helper(), mod.default(), Object.keys(mod));
const { default: renamed, helper: alias } = mod;
console.log(renamed(), alias());named default [ 'default', 'helper' ]
default namedUsing modules in Node.js
Node.js decides how to load a file from its extension and from the nearest package.json. A .mjs file is a module, a .cjs file is CommonJS, and a .js file follows the "type" field of its package, "module" or "commonjs", the default.
{
"name": "example",
"type": "module",
"exports": "./src/index.js",
"engines": { "node": ">=22.12" }
}Three differences catch people. Relative imports need the file extension, so import "./utils.js", not "./utils", because ES module resolution does not search. Node.js built-ins are imported with the node: prefix, which is clearer and cannot be shadowed by a package. And a CommonJS file cannot normally import, but since Node.js 22.12 it can require() an ES module as long as the module does not use top-level await, which eases migration.
In the browser, a module script is written <script type="module" src="app.js"></script>, deferred by default and fetched once per URL.
Where modules stop being the right tool
If you must load code conditionally or lazily, use import() rather than a static import. If you maintain a package that must work for both module systems, publish an ES module build and a CommonJS build through the exports map, or publish ES modules only and require recent Node.js. And in a test environment that mocks modules, remember that live bindings and the cache change how mocking works: a test runner usually replaces a module by URL before it loads, which is why mock calls must come before the import.
The module system is defined in the specification under modules, and MDN's guide to JavaScript modules covers the syntax and the browser behavior.


