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
- Basic dynamic import:
javascript const module = await import("./chart.js"); module.renderChart(data); - Conditional loading:
javascript if (userPrefersDark) { const theme = await import("./dark-theme.js"); theme.apply(); } - 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.