liveBook · Manning

Named export

As explained in Secrets of the JavaScript Ninja, Third Edition

A named export is a module export identified by a name that importers can reference explicitly.

A named export makes a value available from a module under a specific name. Use it when a module exposes several values that callers should choose explicitly. In ESM, `export const homeIsland = "Tsushima"` and `export function getOccupation(...)` create two named exports; an importer selects them inside braces. section 13.1.1

Listing 13.2 Importing named values
import { #A
  homeIsland, #A
  getOccupation as getTitle, #A
} from "./1-export-syntax.ts"; #A

console.assert(
  homeIsland === "Tsushima",
  "The home island is Tsushima",
);
console.assert(
  getTitle("Yotei") === "Ghost of Yotei",
  "The protector of Yotei is a ghost",
);

The import keeps `homeIsland` under its exported name but uses `as` to call `getOccupation` by the local name `getTitle`. Aliasing also resolves clashes between imports with the same name. section 13.1.1

Named and default exports can coexist. A default import appears before the braces containing named imports; a namespace import instead collects the module’s exports for access as properties. The `from` path is resolved by the runtime or compiler, not prescribed by ESM: Node’s ESM imports require file extensions, while TypeScript settings affect which extensions are accepted. section 13.1.1

An exported value that changes

A module exports `rollDice` and `lastDiceRoll`. Each call to `rollDice` reassigns `lastDiceRoll` in that module, and an importer reading `lastDiceRoll` sees the updated value. This is a live binding, not a copied snapshot. The importer cannot reassign it; the exporting module can. section 13.1.1 section 13.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Works through declaration, import aliases, and live bindings, with practical import-path caveats rather than a module-resolution algorithm.
Examples
Uses paired export-and-import files and a dice-roll module whose exported value changes.
What it assumes
Assumes familiarity with TypeScript declarations while showing the ESM export and import forms explicitly.
What you can do after
Build it from scratch by exporting named values, importing them with optional aliases, and reading updated bindings.
How it connects
Connects named exports to default exports, namespace imports, live bindings, and module resolution.

Also explained in

Compare how 3 books explain named export →

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.