If a module exports a variable and later reassigns it, what does an importer see? In an ECMAScript Module (ESM), the import is a live binding: it reflects the exported variable’s current value. It is not a copied value or an ordinary variable the importer can reassign. section 13.1.1
Listing 13.7 Exporting a value that can be reassigned
const rollDice = () => {
const roll1 = Math.ceil(Math.random() * 6);
const roll2 = Math.ceil(Math.random() * 6);
lastDiceRoll = roll1 + roll2;
return lastDiceRoll;
};
let lastDiceRoll = -1;
export { rollDice, lastDiceRoll }; #AThe exporting module declares lastDiceRoll with let. Each call to rollDice assigns it a new result; an export list exposes both the function and variable. section 13.1.1
Listing 13.8 Importing a reassignable value
import {
lastDiceRoll,
rollDice,
} from "./7-random-export.ts";
for (let i = 0; i < 3; i++) {
rollDice();
console.log(lastDiceRoll);
}The importing module calls rollDice three times and reads lastDiceRoll after each call. Each read sees the latest result. section 13.1.1
The distinction is who may assign. The exporting module can update its variable, but assigning to lastDiceRoll in the importing module raises a TypeError. Think of the import as a read-only proxy to the original variable—not as object destructuring, despite the similar-looking named-import syntax. section 13.1.1
