Skip to main content

Dynamic Imports

Modules: Dynamic Imports


How can we import a module dynamically, on-demand?

View Answer:
Interview Response: We can implement dynamic imports by using the import expression. The import(module) expression loads the module and returns a promise that resolves into a module object that contains all its exports. It gets called from any place in our code.

Code Example:

// 📁 say.js
export function hi() {
alert(`Hello`);
}

export function bye() {
alert(`Bye`);
}

// Then dynamic import can be like this

let { hi, bye } = await import('./say.js');

hi();
bye();

Is there a process for importing dynamic JS modules to manage issues?

View Answer:
Interview Response: In simple terms, we can handle errors in dynamic imports the same way we handle errors in promises by using the then and catch methods.

Code Example:

let modulePath = prompt("Which module to load?");

import(modulePath)
.then(obj => <module object>)
.catch(err => <loading error, e.g. if no such module>)

What are the benefits of the dynamic import expression in JS?

View Answer:
Interview Response: The main benefit of dynamic imports is that they allow you to load JavaScript modules dynamically. This implementation makes it useful for lazy-loading or computed module specifier strings. In addition, dynamic imports provide us with a promise, allowing access to the .then and .catch methods for handling (catch error). Dynamic imports work in regular scripts; they don’t require script type="module".

Is the dynamic import expression a JavaScript function?

View Answer:
Interview Response: No, although import() looks like a function call, it’s a special syntax that happens to use parentheses (similar to super()). So, we cannot copy import to a variable or use call/apply with it. It is not a function.

What is tree shaking?

View Answer:
Interview Response: Tree shaking is a type of dead code removal. It implies that unnecessary modules get excluded from the bundle during the build process. It relies on the static structure of ES2015 module syntax ( i.e., import and export). Initially, the ES2015 module bundler 'rollup' promoted this. We have access to several module bundlers, including WebPack, Browserify, Fusebox, and Rollup.