DEV Community

David Rickard
David Rickard

Posted on

Lazy loading Web Components with WebPack in 1 minute

Normally when you define a web component with Lit or FAST you might do something like this:

import { MyComponent } from "./MyComponent";

MyComponent; // Stop tree-shaking
Enter fullscreen mode Exit fullscreen mode

As part of importing the module, it defines the <my-component> element that you want to put in DOM.

That works just fine but now that web component's Javascript is part of the same bundle as whatever was calling it. What if it's just some dialog picker that rarely gets called, or always called far after the main page load?

Just run this line when you need to show that component.

await import("./MyComponent ");
Enter fullscreen mode Exit fullscreen mode

Webpack will see that it's a dynamic import, create a new bundle for it and download it when the code is run. That will define <my-component> and automatically upgrade any of them you have in your DOM already.

I was rather shocked with how easy it was to do. Just remember that if what you are loading in needs to be tree-shaken you'll need to create an intermediate "lazy" module to help Webpack do that.

Top comments (0)