import { LitElement, html } from 'lit-element';
class MyPublic extends LitElement {
render(){
return html`
<p>A paragraph</p>
`;
}
}
customElements.define('my-public', MyPublic);
I defined a public web component like that in MyPublic.js. And then when I need to use it in FooComponent.js, I will import MyPublic.js, when I need to use it in BarComponent.js, I will also import MyPublic.js. It will cause re-definition for my-public.
How to avoid it?
Just import all the web components in index.js, and then don't import it anymore?
When using a bundler, the only way is to ensure the following:
you don't get same component imported in 2 different chunks,
you don't get 2 different versions of the same component installed.
Running npm dedupe usually helps with the latter. Using yarn which performs somewhat similar thing directly when installing dependencies (even without --flaat) also helps.
When using a bundler, the only way is to ensure the following:
- you don't get same component imported in 2 different chunks,
- you don't get 2 different versions of the same component installed.
Running
npm dedupeusually helps with the latter. Usingyarnwhich performs somewhat similar thing directly when installing dependencies (even without--flaat) also helps.
Sorry, what I mean is my own web component which is definitely in my source code rather than third-party modules.
How can I avoid re-definition for a web component in my own code?
How can I avoid re-definition for a web component in my own code?
Browsers de-duplicate any requests to ES module from the same origin.
So, the module containing a source code of your web component will be only parsed and executed once (including customElements.define() call) regardless of where do you import it.
I think @web-padawan answered the question here. Thanks!
Most helpful comment
Browsers de-duplicate any requests to ES module from the same origin.
So, the module containing a source code of your web component will be only parsed and executed once (including
customElements.define()call) regardless of where do you import it.