Basic Dynamic Import Syntax
You'll learn how to use import() as a function that returns a promise, giving you on-demand access to modules.
The Core Idea
Unlike the static import statement you've been using at the top of your files, the import() function lets you load modules dynamically at runtime. Think of it like ordering food: static imports are meal-prep—everything's ready when you start. Dynamic imports are like calling delivery—you request what you need, when you need it.
The key difference is that import() is a function call that returns a promise. That promise resolves to the module's namespace object, containing all its exports.
The Syntax
import('./myModule.js')
.then(module => {
// Use the module here
console.log(module.exportedValue);
module.exportedFunction();
})
.catch(err => {
console.error('Failed to load module:', err);
});
Since it returns a promise, you can also use it with async/await:
async function loadModule() {
try {
const module = await import('./myModule.js');
console.log(module.exportedValue);
module.exportedFunction();
} catch (err) {
console.error('Failed to load module:', err);
}
}
The module object you get back contains all named exports as properties. If there's a default export, it's available as module.default.
When the Loading Happens
The crucial difference: import() doesn't load anything until the line executes. You can put it inside conditions, loops, or event handlers—anywhere regular code can go.
Key Takeaway: import() is a function returning a promise that resolves to a module's namespace object, enabling you to load modules on-demand at runtime rather than upfront.