Dynamic Imports with JavaScript

With the function-like dynamic import() statement:


const lazy = async _ => { 

    const module = await import("./LazyContent.js");
    console.log("const", module.msg);
    console.log("function", module.message());
    const lazyClass = new module.default;
    console.log('class', lazyClass.message());

} 
lazy();

you can load on-demand previously exported classes, functions or primitives:

export default class LazyClass{ 
    message(){ 
        return "lazy today";
    }
}

const msg = "good morning";

const message = _ => { 
    return "hello world";
}

export { msg, message}    

See it in action and from scratch:

A dynamic import was used in the effectiveweb.training to build a hash-based router.

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License