Dynamic Import Syntax
What you'll learn: How to use import() statements to load JavaScript modules on-demand, creating automatic code split points in your application.
The Core Idea
Dynamic imports are JavaScript's built-in way to load modules when you need them, not just at startup. Unlike static import statements at the top of your file, the import() function returns a Promise and can be called conditionally, inside functions, or in response to user actions.
Think of it like streaming vs downloading: Static imports are like downloading an entire movie before watching—you wait upfront. Dynamic imports are like streaming—you load each scene as you need it.
The Syntax
// Static import (loads immediately)
import { heavyFunction } from './heavy-module.js';
// Dynamic import (loads when called)
button.addEventListener('click', async () => {
const module = await import('./heavy-module.js');
module.heavyFunction();
});
The import() function takes a module path string and returns a Promise that resolves to the module object.
Creating Split Points
When bundlers like Webpack or Vite encounter import(), they automatically create a separate chunk:
// This creates a split point
async function loadChart() {
const chartLib = await import('./chart-library.js');
return new chartLib.Chart();
}
Your bundler will generate chart-library.[hash].js as a separate file, loaded only when loadChart() executes.
Practical Pattern
// Load feature only if needed
if (userIsAdmin) {
const adminPanel = await import('./admin-panel.js');
adminPanel.render();
}
Key Takeaway: Dynamic import() statements let you split code naturally by writing conditional or delayed imports, and modern bundlers automatically generate separate chunks for lazy-loaded modules.