Dynamic Import() in Modules
Load modules on demand with dynamic import().
The import() Expression
Unlike the static import declaration, import("./module.js") is an expression that returns a Promise resolving to the module's namespace. It works anywhere — inside functions, conditions, even inside non-module scripts.
Code Splitting
Dynamic import is the primary code-splitting mechanism. A route handler can defer loading the route's code until the user navigates: const mod = await import("./routes/admin.js"). The route's bytes never download until they are needed.
document.getElementById("settings-btn").addEventListener("click", async () => {
const { renderSettings } = await import("./settings.js");
renderSettings();
});All lessons in this course
- ES Module Scripts type=module
- Import Maps importmap
- Dynamic Import() in Modules
- Module Federation Basics