Lit-element: how to avoid re-definition web component in lit-element?

Created on 19 Aug 2019  路  4Comments  路  Source: Polymer/lit-element

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?

Most helpful comment

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.

All 4 comments

When using a bundler, the only way is to ensure the following:

  1. you don't get same component imported in 2 different chunks,

  2. 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:

  1. you don't get same component imported in 2 different chunks,
  2. 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.

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kurukururuu picture kurukururuu  路  3Comments

vdegenne picture vdegenne  路  4Comments

mercmobily picture mercmobily  路  3Comments

Tanbouz picture Tanbouz  路  5Comments

chrismbeckett picture chrismbeckett  路  3Comments