liveBook · Manning

Module namespace object

As explained in Secrets of the JavaScript Ninja, Third Edition

An object that exposes a module’s exported bindings as properties.

Need one object that represents a module’s exports? In ESM, `import * as characters` creates a namespace object whose properties are the export names; a default export appears under `default`. Unlike a typical mutable object, the namespace is sealed and its properties are read-only. section 13.1.1

Listing 13.6 Importing a module as a namespace
import * as characters from "./4-default-export.ts"; #A

console.assert(
  characters.default === "Ranma",
  "The default export is Ranma",
);
console.assert(
  Object.keys(characters).length === 3,
  "All 3 exports are included in the namespace",
);

This import gathers the default and named character exports under one namespace. section 13.1.1

A namespace import is useful when you need to inspect exports without naming each one in advance. When you only need selected exports, import those directly: bundlers can then omit unused code during tree-shaking. section 13.1.1

CommonJS interoperability

In Node.js, requiring an ESM module returns its namespace object. Access the default export as `.default`; it is not the whole object. This differs from importing a CommonJS module into ESM, where the whole CommonJS exports object is treated as the default import. section 13.2.1 section 13.1.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines export-name properties and shallow immutability, then demonstrates access; it does not detail runtime internals.
Examples
Uses a character module with default and named exports, scans exported strings, and demonstrates Node.js requiring ESM.
What it assumes
Assumes familiarity with ESM imports and exports, and contrasts that module model with CommonJS.
What you can do after
Understand how namespace properties expose module exports and how the default property behaves across ESM and CommonJS.
How it connects
Connects ESM namespace imports and named/default exports to CommonJS interoperability and bundler tree-shaking.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.