Lesson 79 +20 XP

Import Everything and Dynamic Import

Import Everything and Dynamic Import

Sometimes you want to import a whole module at once, or load it only when needed.

Import everything as a namespace

import * as math from "./math.js";
math.add(2, 3); // 5
math.pi;        // 3.14

The * as math syntax bundles all exports into one object.

Why namespace imports?

  • Convenient when you use many exports.
  • Keeps the imported names grouped under one name.

Dynamic import

The import() function loads a module only when needed. It returns a promise:

async function loadUtils() {
  const utils = await import("./utils.js");
  utils.help();
}

Why dynamic import?

  • Load code only when the user needs it (code splitting).
  • Faster initial page load.
  • Useful for optional features.

Static vs dynamic

  • Static import (import x): at the top, loaded upfront.
  • Dynamic import (import()): on demand, returns a promise.

TL;DR

  • import * as name imports everything as an object.
  • import() loads modules on demand.
  • Dynamic import returns a promise.
  • Use it to load code only when needed.