How to use dynamic import in JavaScript

· Category: JavaScript

Short answer

import() returns a Promise that resolves to the module namespace, allowing you to load code conditionally or on user interaction.

Steps

  1. Basic dynamic import: javascript const module = await import("./chart.js"); module.renderChart(data);
  2. Conditional loading: javascript if (userPrefersDark) { const theme = await import("./dark-theme.js"); theme.apply(); }
  3. Error handling: javascript try { const lib = await import("optional-lib"); } catch (err) { console.error("Lib not available"); }

Tips

  • Use dynamic imports to reduce initial bundle size.
  • Most bundlers automatically code-split at dynamic import boundaries.

Common issues

  • Dynamic import paths must be statically analyzable by some bundlers; avoid fully dynamic strings.
  • In Node.js, use file URLs or absolute paths for dynamic imports of local modules.