Sub topic 4
Working with the Module Namespace Object
This chapter assumes you know import/export syntax, promises with async/await, and the basic form of import() from the previous chapter. Here the focus is on what the promise resolves to: the module namespace object.
What import() Gives You
import() never resolves to a single function or value. It resolves to a namespace object, which has one property for each export of the module. Named exports keep their own names. The default export is stored under the property name default.
Here is a small module to work with:
// logger.js
export const LEVELS = { info: 'INFO', warn: 'WARN' };
export default function log(level, message) {
console.log(`[${level}] ${message}`);
}And here is the code that loads it:
// main.js
async function main() {
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); // true
console.log(Object.keys(loggerModule)); // [ 'LEVELS', 'default' ]
}
main();default is a reserved word, so it can't be a variable name. That is why destructuring has to rename it with { default: logAgain }.
Properties of the Namespace Object
The namespace object has some properties that ordinary objects do not:
| Property | Behavior |
|---|---|
| Cached | The same resolved specifier returns the same namespace object every time. The module is evaluated only once. |
| Live bindings | Each property reads the exporting module's current value of that export. |
| Read-only | You cannot assign, add, or delete properties. In strict mode, trying throws a `TypeError`. |
| Null prototype | It has no `Object.prototype`, so it has no `hasOwnProperty` or `toString` of its own. |
| Sorted keys | Export names come back in alphabetical order. |
| Tag | `Object.prototype.toString.call(ns)` returns `[object Module]`. |
Live bindings are the property people most often miss:
// counter.js
export let count = 0;
export function increment() {
count++;
}// use-counter.js
async function run() {
const counter = await import('./counter.js');
const { count } = counter; // copies the current value: 0
counter.increment();
console.log(counter.count); // 1 (live)
console.log(count); // 0 (snapshot)
}
run();When you destructure, you get a snapshot of the value at that moment. When you read through the namespace object, you always get the current value.
Common Errors
- Calling the namespace as a function.
(await import('./logger.js'))('info', 'x')throwsTypeError: ... is not a function. Use.defaultto get the default export. - Mutating the namespace.
loggerModule.extra = 1throws in modules, because module code always runs in strict mode. Copy the exports with{ ...loggerModule }if you need an object you can change. - Expecting a fresh instance. Importing the same module twice does not reset its state. Use an exported factory function if you need separate copies.
- Exporting
then. If a module exports a function namedthen, theimport()promise treats the namespace as a thenable and calls that function. Don't usethenas an export name.
Exercise
A module theme.js contains export let mode = 'light'; export function toggle() { mode = mode === 'light' ? 'dark' : 'light'; }. After const ns = await import('./theme.js'); const { mode } = ns; ns.toggle();, what do ns.mode and mode evaluate to, and why?
Show answer
ns.mode is 'dark' because namespace properties are live bindings to the module's current value. mode is still 'light' because destructuring copied the value before toggle() ran.
Exercise
Write a single destructuring statement that loads ./logger.js and binds its default export to log and its named export LEVELS to LEVELS.
Show answer
const { default: log, LEVELS } = await import('./logger.js');