Skip to content

Dynamic Import

In one line

Dynamic import() is an expression that loads an ES module on demand at runtime, returning a promise.

In simple words

Dynamic import() lets you load a module at runtime, on demand, instead of at the top of the file. It returns a Promise that resolves to the module namespace object. This enables code splitting, lazy loading, and conditional feature loading.

Static imports (import x from 'y') are evaluated eagerly when the module loads. Dynamic import (const x = await import('y')) happens only when the line runs. Bundlers like Webpack, Rollup, and Vite use this to split your bundle into chunks that load only when needed, shrinking the initial download.

Use dynamic import for route-level code splitting (load the admin module only when the user visits /admin), for heavy optional featuresA features (load a PDF library only when the user clicks export), and for feature detection. The syntax is import(), called like a function.

Example

javascript
// Load the admin module only when needed
async function loadAdmin() {
  const admin = await import("./admin-panel.js");
  admin.showPanel();
}

// Conditional loading based on feature
if (user.role === "admin") {
  loadAdmin();
}

// Default export
const math = await import("./math.js");
console.log(math.default.add(2, 3)); // 5

import() returns a promise resolving to the module. The module (and its chunk) loads only when the line executes.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary