Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 13, 2022 03:10 am GMT

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

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 ");

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.


Original Link: https://dev.to/randomengy/lazy-loading-web-components-with-webpack-in-1-minute-2l3d

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To