liveBook · Manning

Default import

As explained in Secrets of the JavaScript Ninja, Third Edition

An import that binds a module's default export to a local name.

A default import binds a module’s default export to a local name chosen by the importer. That name is not the original export’s identifier, and the import does not make the whole module an object. section 13.1.1

Listing 13.5 Importing a default value along with named values
import hero, { #A
  tsundere, #A
  yandere, #A
} from "./4-default-export.ts"; #A

console.assert(
  hero === "Ranma",
  "Ranma is the hero",
);
console.assert(
  tsundere === "Akane",
  "Akane is the tsundere",
);
console.assert(
  yandere === "Shampoo",
  "Shampoo is the yandere",
);

The default binding can appear alongside named imports from the same module. section 13.1.1

A default export is not special beyond its import syntax: it can also be written as `default as hero` inside a named import list. Because consumers choose its name, projects may prohibit default exports to avoid inconsistent naming. section 13.1.1

Interop can change what a default import refers to. When ESM is compiled to CommonJS, its exports are placed on an object; an ESM consumer may receive that whole object as the default import, with the intended value under its `default` property. Dual ESM and CommonJS entry points can avoid this mismatch, at the cost of build complexity and package bloat. section 13.2.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines consumer-chosen naming, contrasts import forms, and traces the CommonJS compilation mismatch for ESM consumers.
Examples
Uses a string default export alongside named character exports, then shows the CommonJS default-object mismatch.
What you can do after
Apply ESM import syntax to bind a default export locally, including alongside named imports.
How it connects
Connects default imports to ESM exports, named imports, namespace imports, CommonJS, and dual vending.

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.