Dynamic import lets an application defer loading a module until a user needs it, reducing the code required by the initial bundle. A button can load a large module only after it is clicked. section 11.0 section 11.1.4
The import() expression returns a promise that resolves to the exported module object. Access default exports through module.default and named exports through properties such as module.sayHi, or destructure them after awaiting the promise. section 11.1.4
Load a module after a button click
function handleClick() { import("./helloModule").then(({default: showMessage, sayHi}) => { showMessage("messagePara", "Hello World!"); sayHi("hiPara"); }); } The module is not loaded until handleClick runs, and its exports become available when the promise resolves. section 11.1.4
Listing 11.4 Dynamically loading code with the import function (index.js)
function handleClick() {
import("./helloModule") #1
.then((module) => { #2
module.default("messagePara", "Hello World!"); #3
module.sayHi("hiPara"); #3
});
}
document
.getElementById("btnMessages")
.addEventListener("click", handleClick);
#1 Call the import function to dynamically load a module.
#2 Assign the module to a local variable.
#3 Use the module properties to call the exported functions.
Shows the complete event-handler pattern: call import(), receive the resolved module, and invoke its default and named exports. section 11.1.4
