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.

// index.js (main app file)
console.log("App loading...");

const chatModuleButton = document.getElementById('chat-module-button');

chatModuleButton.addEventListener('click', async () => {
    try {
        const chatModule = await import('./modules/chat'); // Import only when clicked
        chatModule.init(); // Initialize the chat module 
    } catch (error) {
        console.error("Error loading chat module:", error);
    }
});

// ./modules/chat.js (Chat module code)
export function init() {
    console.log("Chat module loaded!");
    // ... Chat functionality implementation 
}

Explanation:

  • The chatModuleButton triggers the dynamic import of ./modules/chat.

  • The await keyword pauses execution until the import is complete.

  • Once imported, chatModule.init() initializes the chat module's functionality.

Last updated