🧨 Dynamic Import
Dynamic import allows you to load modules only when needed, rather than at the beginning of your script. It’s a feature of ES2020 using the import() function, which returns a promise.
🧠 Syntax:
import('module-path')
.then(module => {
// Use the imported module
})
.catch(err => {
// Handle errors
});🚀 Use Case Examples
✅ Example: Load a utility file when needed
button.addEventListener('click', async () => {
const math = await import('./math.js');
console.log(math.add(5, 3));
});math.js
export function add(a, b) {
return a + b;
}
✅ The module is loaded only when the button is clicked, not on initial page load.
🔄 await + Dynamic Import (in async function)
async function loadUtils() {
const { formatDate } = await import('./utils.js');
console.log(formatDate(new Date()));
}🤖 Example: Conditional Import
if (user.role === 'admin') {
import('./admin-tools.js').then(module => {
module.initAdminPanel();
});
}🧩 Compared to Static Import
// Static import (always loaded)
import { add } from './math.js';// Dynamic import (loaded when needed)
const { add } = await import('./math.js');📦 Why Use Dynamic Imports?
Benefit | Description |
|---|---|
🔄 Code Splitting | Reduces initial load time by loading modules only when needed |
⚡ Performance | Helps in lazy loading large libraries or infrequently used features |
🧪 Conditional Imports | You can import modules based on conditions (e.g. user role, environment) |
✅ Works in | Returns a promise, which makes it async/await friendly |
🔥 Real World Use Cases
Route-based code splitting in React apps (React.lazy)
Loading large charting libraries only on pages where charts are shown
Conditionally loading polyfills or dev-only tools
❗Note:
Works only in modules (
type="module"in HTML or.mjsfiles)You cannot use dynamic import with CommonJS
require()