Dynamic Imports
20 January, 2023
3
3
2
Contributors
JavaScript dynamic imports allow you to load modules at runtime instead of compile time. This means you can load modules only when needed rather than loading all modules at the start of the application. This can be useful for improving the performance of your application, especially for large and complex applications.
Dynamic imports use the import()
function, which returns a promise that resolves to the exported module.
For example:
// import a module at runtime
async function loadModule() {
const module = await import('./math.js');
console.log(module.add(1, 2)); // 3
}
loadModule();
Dynamic imports are supported in modern browsers and Node.js version 14.7 and above.
It's also possible to use await
inside top-level code, but it requires wrapping it in an async
function.
(async () => {
const module = await import('./math.js');
console.log(module.add(1, 2)); // 3
})();
In case you are new to async/await and JavaScript promises, please take a look into this show: https://www.showwcase.com/show/16131/javascript-async-and-await-in-plain-english-please
Dynamic imports are also helpful when you want to load a module conditionally based on user input or other runtime conditions.