In JavaScript, you can dynamically import a module using the import()
function, which is an asynchronous operation. The import()
function allows you to load a module at runtime, given the full path (either relative or absolute).
Here’s how to dynamically import a module by providing its full path:
Syntax:
import(modulePath)
.then(module => {
// Use the imported module
console.log(module); // module is the imported module object
})
.catch(err => {
console.error('Error loading module:', err);
});
modulePath
: This is the path to the module you want to load, provided as a string. The path can be relative (e.g.,'./module.js'
) or absolute (e.g.,'https://example.com/module.js'
).
Example with Relative Path:
If you have a file structure like this:
/project
/modules
math.js
app.js
And you want to dynamically import math.js
from app.js
, you can do this:
// app.js
const modulePath = './modules/math.js';
import(modulePath)
.then(mathModule => {
console.log(mathModule); // Access the exported members of math.js
console.log(mathModule.add(2, 3)); // Assuming math.js exports an add function
})
.catch(err => {
console.error('Error loading module:', err);
});
Example with Absolute Path (for Web URLs):
You can dynamically import modules from external URLs:
const modulePath = 'https://example.com/modules/math.js';
import(modulePath)
.then(mathModule => {
console.log(mathModule); // Access the exported members of the module
})
.catch(err => {
console.error('Error loading module:', err);
});
Using ES6 Named or Default Exports:
If your module uses named exports or default exports, you can destructure them when importing:
Named Export Example:
// math.js
export const add = (a, b) => a + b;
// app.js
const modulePath = './modules/math.js';
import(modulePath)
.then(({ add }) => {
console.log(add(2, 3)); // Using the 'add' function directly
})
.catch(err => {
console.error('Error loading module:', err);
});
Default Export Example:
// math.js
export default {
add: (a, b) => a + b,
};
// app.js
const modulePath = './modules/math.js';
import(modulePath)
.then(mathModule => {
console.log(mathModule.add(2, 3)); // Accessing the default object
})
.catch(err => {
console.error('Error loading module:', err);
});
Important Notes:
- Dynamic import returns a Promise, so you need to use
.then()
orawait
(if inside an async function). - Relative paths (e.g.,
./module.js
) are resolved based on the location of the file that callsimport()
. - External URLs: You can use dynamic imports for modules hosted on external servers or CDNs, but this requires the server to return the module with the correct MIME type (e.g.,
application/javascript
).
Using await
with import()
(inside an async function):
If you want to use await
instead of .then()
, you must place the dynamic import inside an async
function:
async function loadModule() {
const modulePath = './modules/math.js';
try {
const mathModule = await import(modulePath);
console.log(mathModule.add(2, 3)); // Assuming math.js exports an 'add' function
} catch (err) {
console.error('Error loading module:', err);
}
}
loadModule();
Â
import()
is used to dynamically load modules in JavaScript.- You can specify the full path of the module (relative or absolute).
- Use
.then()
to handle the resolved module, or useawait
inside anasync
function.
This approach works well for loading modules based on user actions, configurations, or conditions at runtime.