Sub topic 4
Working with the Module Namespace Object
This chapter assumes you already know ES module import/export syntax, promises with async/await, and the basic import() call from the previous chapter. Every successful import() resolves to one value, the module namespace object. Nearly all the surprises with dynamic imports come from how that object behaves, so it is worth learning it properly.
What the Promise Resolves To
import('./logger.js') does not resolve to the default export, a copy of the exports, or a plain object. It resolves to a special object with one property per export of the target module. The static form import * as ns from './logger.js' gives you the same object.
// logger.js
export const LEVELS = { info: 'INFO', warn: 'WARN' };
export default function log(level, message) {
console.log(`[${level}] ${message}`);
}// main.js
const loggerModule = await import('./logger.js');
const log = loggerModule.default;
// Equivalent destructuring form
const { default: logAgain, LEVELS } = await import('./logger.js');
log(LEVELS.info, 'ready');
console.log(log === logAgain); // trueBoth await expressions give back the same object, so log and logAgain are the same function. The module was fetched and evaluated once. The second call reused the cached instance.
Default Exports Are Just a Property Named `default`
The module system has no separate slot for "the default export". export default creates an export whose name is default, so it shows up on the namespace as ns.default. These three declarations all produce that property:
| Export form | Namespace property | Notes |
|---|---|---|
| `export default function log() {}` | `ns.default` | The function's `name` is `"log"` |
| `export default () => {}` | `ns.default` | Anonymous default functions get `name === "default"` |
| `export { log as default }` | `ns.default` | Renaming an existing binding |
default is a reserved word, so you cannot use it as a bare variable name. You have to rename it when you destructure:
// SyntaxError: Unexpected reserved word
// const { default } = await import('./logger.js');
// Correct
const { default: log } = await import('./logger.js');If a module only matters for its default export, a small helper saves you repeating .default:
const importDefault = (specifier) => import(specifier).then((m) => m.default);
const log = await importDefault('./logger.js');
log('INFO', 'loaded via helper');The Object Is Exotic, Not Plain
The namespace object is a special ("exotic") object with fixed rules. You can check them yourself:
// counter.js
export let count = 0;
export function increment() {
count++;
}// inspect.js
const ns = await import('./counter.js');
console.log(Object.getPrototypeOf(ns)); // null
console.log(Object.prototype.toString.call(ns)); // [object Module]
console.log(Object.isExtensible(ns)); // false
console.log(Object.keys(ns)); // [ 'count', 'increment' ]
console.log(Object.getOwnPropertyDescriptor(ns, 'count'));
// { value: 0, writable: true, enumerable: true, configurable: false }
try {
ns.count = 99;
} catch (err) {
console.log(err.constructor.name); // TypeError
}
try {
ns.extra = 1;
} catch (err) {
console.log(err.constructor.name); // TypeError
}These rules have practical effects:
- Null prototype.
ns.hasOwnPropertyisundefined. UseObject.hasOwn(ns, 'name')or'name' in nsto test whether an export exists. - Sorted keys. Export names are listed in code-unit order, not source order. Don't rely on
Object.keys(ns)to match how the file was written. - No writes. The descriptor says
writable: true, yet assignment always fails. Module code is strict mode, so the failure throws aTypeError. Importers cannot replace another module's exports. Symbol.toStringTagis"Module". This is howconsole.logand debuggers recognize a namespace.
If you need a normal, mutable object, for example to merge in defaults, copy it: const plain = { ...ns }. The copy is a snapshot and loses the live link described next.
Live Bindings, and How Destructuring Breaks Them
A namespace property is a live view of the variable inside the module, not a stored copy. When the module changes the variable, the property shows the new value. Destructuring copies the current value into a local variable, so the link is gone after that.
// live.js
const ns = await import('./counter.js');
const { count, increment } = ns;
increment();
increment();
console.log(ns.count); // 2 (live view)
console.log(count); // 0 (snapshot taken at destructuring time)Functions, classes, and constants are not affected, because their bindings never change. Destructuring { increment } or { default: log } is safe. The trap applies only to export let (and export var) bindings that the module reassigns later, such as counters, lazily set singletons, or a ready flag. Read those through the namespace each time.
Caching and Identity
The runtime keeps one module instance per resolved URL (or file path in Node.js), so all of these give back the same namespace object:
// identity.js
import * as staticNs from './counter.js';
const a = await import('./counter.js');
const b = await import('./counter.js');
console.log(a === b); // true
console.log(a === staticNs); // trueSo a module's top-level code runs only once, however many times or places you import it. State in that module is shared by everyone. Two specifiers that resolve to different URLs create two separate instances with separate state, for example ./counter.js and ./counter.js?v=2. That can be a hidden source of duplicated state.
The `then` Export Gotcha
import() fulfills its promise with the namespace object, and promise fulfillment checks whether the value is "thenable". If the target module exports a function named then, the promise machinery calls it as though the namespace were a promise:
// thenable.js
export function then(resolve) {
resolve('not the namespace');
}// surprise.js
const result = await import('./thenable.js');
console.log(result); // 'not the namespace'A static import * as ns from the same file works normally. Only the promise-based path is affected. If then never calls resolve, the await hangs forever. Don't name an export then in any module that might be loaded dynamically.
Missing Exports Fail Quietly
A static import of a name that doesn't exist is a SyntaxError at link time, before any code runs. Reading a missing property from a namespace just gives undefined:
// missing.js
const { renderChart } = await import('./counter.js');
console.log(renderChart); // undefined, no error yet
renderChart(); // TypeError: renderChart is not a functionWhen the specifier is computed or comes from a plugin, check the shape before you use it:
// plugin-loader.js
export async function loadPlugin(specifier) {
const ns = await import(specifier);
if (typeof ns.default !== 'function') {
throw new TypeError(`${specifier} has no default export function`);
}
return ns.default;
}One more edge case: in a circular dependency, a namespace can be handed out before its module has finished evaluating. Reading a let, const, or class export that has not been initialized yet throws a ReferenceError. A later chapter covers this together with top-level await.
Exercise
A module state.js contains export let user = null; export function login(name) { user = name; }. Another module runs const { user, login } = await import('./state.js'); login('ada'); console.log(user);. What is logged, and how would you change the code so it logs 'ada'?
Show answer
It logs null. Destructuring copied the value of user before login reassigned it. To fix it, keep the namespace, const ns = await import('./state.js'); ns.login('ada'); console.log(ns.user);, which reads the live binding and logs 'ada'.
Exercise
You run const ns = await import('./config.js'); ns.debug = true; and get a TypeError. Why, and what is a correct way to get a configuration object you can modify?
Show answer
The namespace object is non-extensible and its properties cannot be assigned, and module code runs in strict mode, so the assignment throws. Make a mutable snapshot, for example const cfg = { ...ns, debug: true };. Or have config.js export a setter function or a mutable object as its default export.
Exercise
Why does await import('./a.js') resolve to a string when a.js exports function then(r) { r('x'); }, while import * as a from './a.js' gives the normal namespace?
Show answer
The import() promise is fulfilled with the namespace object. Promise resolution treats any object with a callable then property as a thenable and calls that method, so the promise takes the value the method resolves with. The static import does not go through promise resolution, so it binds the namespace directly.