Question 37
Question
Can you explain how to use dynamic imports with import() function in ES6 modules with 1 practical use case?
Answer
Basic Syntax:
const modulePromise = import('./myModule.js'); // Imports 'myModule.js' asynchronously
modulePromise.then(
// Resolve: Module loaded successfully
({ default, ... }) => {
console.log("Module imported:", default);
// Use the imported functions/variables
default.doSomething();
},
// Reject: Error loading module
error => {
console.error("Error importing module:", error);
}
);Practical Use Case: On-Demand Loading of Features
Imagine building a web application with different features (e.g., a chat, image editor, analytics dashboard). You don't want to load all these features at once, as it might slow down the initial page load. Dynamic imports let you load them only when needed.
Explanation:
The
chatModuleButtontriggers the dynamic import of./modules/chat.The
awaitkeyword pauses execution until the import is complete.Once imported,
chatModule.init()initializes the chat module's functionality.
Last updated