Dynamic Imports in JavaScript Modules
Dynamic Imports:
Write a JavaScript programme that uses dynamic imports to load a module and invoke its function asynchronously.
Solution-1: Using import() with Async Function
JavaScript Code:
File: mathOperations.js
// mathOperations.js
// Exporting a function from mathOperations.js
export const multiply = (a, b) => a * b; // Multiplies two numbers
File: main.js
//main.js
// Async function to dynamically import and use the module
async function loadAndMultiply(a, b) {
// Dynamically importing the module
const mathModule = await import('./mathOperations.js');
// Using the imported function
console.log(mathModule.multiply(a, b)); // Logs the result of multiplication
}
// Calling the function
loadAndMultiply(4, 5); // Logs 20
Output:
20
Explanation:
- The multiply function is exported from mathOperations.js.
- In main.js, an async function loadAndMultiply is defined to dynamically import the module.
- The import() function is used to load the module when needed, ensuring the code is split into chunks and loaded on demand.
- The multiply function from the dynamically imported module is then invoked to calculate the product.
Solution-2: Using import() Inside a Non-Async Function
JavaScript Code:
File: mathOperations.js
// mathOperations.js
// Exporting a function from mathOperations.js
export const multiply = (a, b) => a * b; // Multiplies two numbers
File: main.js
//main.js
// Using dynamic import inside a regular function
function loadAndDivide(a, b) {
import('./mathOperations.js')
.then((mathModule) => {
console.log(mathModule.multiply(a, b)); // Logs the result of multiplication
})
.catch((error) => {
console.error('Error loading the module:', error); // Handles import errors
});
}
// Calling the function
loadAndDivide(6, 3); // Logs 18
Output:
18
Explanation:
- The multiply function is exported from mathOperations.js.
- In main.js, a regular function loadAndDivide is defined.
- The import() function is used with a .then() chain to dynamically load the module.
- The multiply function is called after the module is successfully loaded, and errors are handled using .catch().
Improve this sample solution and post your code through Disqus
Previous: Import Aliases in JavaScript Modules.
Next: Mastering Conditional Imports in JavaScript Modules.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics