liveBook · Manning

Dynamic import

As explained in Secrets of the JavaScript Ninja, Third Edition

Dynamic import is an expression that loads a module at runtime and returns a promise for its module namespace object.

Dynamic import, written import(...), loads a module at runtime rather than resolving it with a static import. It enables lazy loading: the imported code is not parsed until needed, which can avoid parsing an entire package barrel when only part of it is used. section 13.1.2 section 13.4

Listing 13.11 A module at the package root
export const lazyGetRandomTurtle = async () => {
  const { getRandomTurtle } =
    await import("./ninjas/turtles.js"); #A
  return getRandomTurtle();
};

A package-root function waits until it is called to import the turtle submodule, then calls its exported function. section 13.1.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains runtime versus parse-time resolution and demonstrates deferred loading, but does not detail loading internals.
Examples
Demonstrates awaiting a turtle submodule import inside a package-root function.
What you can do after
Apply it to defer a package submodule until a function is called.
How it connects
Connects runtime loading with static imports, ECMAScript modules, barrel files, and tree-shaking.

Also explained in

Compare how 3 books explain dynamic import →

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.