w3resource

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().

For more Practice: Solve these Related Problems:

  • Write a JavaScript program that dynamically imports a module when a button is clicked and then calls a function from the module.
  • Write a JavaScript program that uses dynamic import() to load a configuration file asynchronously and applies its settings.
  • Write a JavaScript program that dynamically imports a module based on user input and logs the module’s exported functions.
  • Write a JavaScript program that loads a module dynamically and handles any errors during the import process gracefully.

Go to:


PREV : Import with Alias.
NEXT : Conditional Imports.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.