
Imports Are Live Bindings, Not Copies: How ES Modules Really Work
- كاتب موثّق
- ES2025
محتويات المقال
counter.js proves the counter works: 1, 2, 3. The header re-renders every few seconds and reads unread each time, yet never sees the new value. After an afternoon of debugging, the team concludes that imports are copies and starts wrapping every value in a getter function. The real cause is one line at the bottom of the counter module: export default unread;.
The common misconception
import runs the module file and gives you a copy of its exports as they were at that moment. Two files importing the same module get two separate copies, and later changes in the module don't reach them.
import { x } from "./a.js" looks a lot like const { x } = require("./a.js"), and in CommonJS that destructuring really does copy each property's value at that instant, because require returns an ordinary object. And the one case where ES modules do hand out a fixed value, export default with an expression, looks exactly like a snapshot. Hit it once and the whole model seems confirmed.
What actually happens
One module, evaluated once
<script> tags reference it, and the same holds for imports. In browsers, the HTML Standard guarantees it with the module map: it's keyed by the module's URL and type, and it exists so that imported module scripts are fetched, parsed and evaluated once per document or worker. Every importer gets the same module instance, so module-level state is shared app-wide. Imports are also hoisted: MDN notes that their side effects happen before the rest of the importing module's code runs.
Named imports are live bindings
console.log("session.js runs");export let userId = null;export function signIn(id) { userId = id;}import { userId } from "./session.js";export const showUser = () => console.log(`header sees ${userId}`);import { userId, signIn } from "./session.js";import { showUser } from "./header.js"; // imports session.js tooconsole.log(userId); // nullsignIn("u-42");console.log(userId); // u-42: the binding is liveshowUser(); // header sees u-42: one shared module instanceapp.js with Node 24, and in Chromium as module scripts, prints session.js runs exactly once, first, and then the three lines in the comments. signIn assigned the exporter's variable, and both importers saw it.
Read-only, but not frozen
app.js tries userId = "admin", it throws TypeError: Assignment to constant variable., exactly as MDN's example shows: only the exporting module can assign its variables. That doesn't make exported objects immutable, though. MDN's guide compares imports to const: you can't reassign the name, but you can still change an object's properties, and every importer will see that change, since they all share the object.
The one snapshot: export default with an expression
export default accepts any expression, and the ECMAScript specification says what happens to it: the expression is evaluated once, when that line runs, and the resulting value is stored in a hidden binding named *default*. Nothing ever assigns that hidden binding again. So export default unread; exports the number unread held at that moment, not the variable. export { unread as default } exports the variable itself under the name default:
let unread = 0;export function markUnread() { unread++;}export default unread; // evaluates `unread` once and exports that valuelet unread = 0;export function markUnread() { unread++;}export { unread as default }; // exports the variable itselfimport unread, { markUnread } from "./counter.js";markUnread();markUnread();console.log(`unread: ${unread}`);counter.js, this prints unread: 0 in both Node 24 and Chromium; with the right one, unread: 2. For export default, the importer can't tell the difference: the export line decides.
export let x or export { x } | x |
export { x as default } | default |
export default x; (or any expression) | x had when that line ran |
import * as ns, then ns.x | |
const { x } = ns in the importer |
How to apply it in your project
Search for default exports of variables Look for export defaultfollowed by a variable that is later reassigned. Change it to a named export or toexport { name as default }.Don't copy imports into module-level constants const currentUser = userId;at the top of a module takes a snapshot when the module runs. Read the import where you need it, or call a getter.Change state through the exporter Export functions like signInthat update the module's own variables, rather than letting importers mutate exported objects from all over the app.Treat module state as an app-wide singleton Every importer shares it, and so do tests running in the same process. Export a reset()for tests, or move the state into a factory function that creates a fresh instance.
Key takeaways
A module is evaluated once per page or worker, and every importer shares that single instance. Named imports are live, read-only views of the exporter's variables, not copies. Importers can't reassign an import, but they can mutate an exported object, and everyone sees the change. export defaultwith an expression exports a value captured once; use a named export orexport { x as default }for state that changes.A different URL, even just a query string, means a different module instance with its own state.
التعليقات (0)