ECMAScript question detail
Dynamic Import
Static imports supports some of the important use cases such as static analysis, bundling tools, and tree shaking, it is also it's desirable to be able to dynamically load parts of a JavaScript application at runtime.
The new feature dynamic import is introduced to load a module conditionally or on demand. Since it returns a promise for the module namespace object of the requested module, the module can be resolved or import can now be assigned to a variable using async/await as below
<script>
const moduleSpecifier = './message.js';
import(moduleSpecifier)
.then((module) => {
module.default(); // Hello, default export
module.sayGoodBye(); //Bye, named export
})
.catch(err => console.log('loading error'));
</script>
<script>
(async function() {
const moduleSpecifier = './message.js';
const messageModule = await import(moduleSpecifier);
messageModule.default(); // Hello, default export
messageModule.sayGoodBye(); //Bye, named export
})();
</script>
and the imported module appears with both default and named exports
export default () => {
return "Hello, default export";
}
export const sayGoodBye = () => {
return "Bye, named export"
}
Note: Dynamic import does not require scripts of type="module"