Dynamic Import
Dynamic Import
Section titled “Dynamic Import”Introduction
Section titled “Introduction”Dynamic imports (import()) load modules on demand, at runtime. Unlike static imports, they return a Promise and can be called conditionally.
Basic Usage
Section titled “Basic Usage”button.addEventListener('click', async () => { // Module is loaded only when button is clicked const { format } = await import('./formatter.js'); console.log(format('Hello'));});Use Cases
Section titled “Use Cases”1. Route-based Code Splitting
Section titled “1. Route-based Code Splitting”const routes = { '/home': () => import('./pages/home.js'), '/about': () => import('./pages/about.js'), '/dashboard': () => import('./pages/dashboard.js'),};
async function navigate(path) { const module = await routes[path](); module.render();}2. Conditional Loading
Section titled “2. Conditional Loading”async function loadChart() { if (typeof window !== 'undefined') { const { Chart } = await import('chart.js'); return new Chart(ctx, config); }}3. Feature Flags
Section titled “3. Feature Flags”async function loadFeature(featureName) { const features = { analytics: () => import('./features/analytics.js'), chat: () => import('./features/chat.js'), export: () => import('./features/export.js'), };
if (features[featureName]) { const module = await features[featureName](); module.init(); }}Default and Named Imports
Section titled “Default and Named Imports”// Named exportconst { add, PI } = await import('./utils.js');
// Default exportconst User = (await import('./User.js')).default;// Or simpler:const { default: User } = await import('./User.js');Static vs Dynamic
Section titled “Static vs Dynamic”| Aspect | Static import | Dynamic import() |
|---|---|---|
| Timing | At parse time | At runtime |
| Conditional | No | Yes |
| Returns | Nothing (hoisted) | Promise |
| Use case | Core dependencies | Lazy loading |
Best Practices
Section titled “Best Practices”- Use static imports for critical dependencies
- Use dynamic imports for code splitting
- Handle loading states for dynamic imports
- Preload critical dynamic imports with
<link rel="preload">
Summary
Section titled “Summary”import()returns a Promise of the module- Enables lazy loading and code splitting
- Supports both named and default imports
- Use for route-based splitting, feature flags, conditional loading