Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': this name has already been used with this registry

前端 未结 3 1500
野趣味
野趣味 2020-12-17 20:42

Uncaught DOMException: Failed to execute \'define\' on \'CustomElementRegistry\': this name has already been used with this registry at http://127.0.0.1:8000/components/

相关标签:
3条回答
  • 2020-12-17 21:16

    Well, this worked for me, with no Typescript warnings,

    if (!customElements.get('the-element')) { customElements.define('the-element', HTMLTheElement); }
    

    Hope someone will find this useful.

    Cheers.

    0 讨论(0)
  • 2020-12-17 21:33

    It is unwise to use the answers above. You want it to fail! The reason being is that your NPM should be deduping duplicate packages, so the fact that you see a certain component being defined on the custom elements registry more than once is a crucial error that you need to debug why the same component is registered more than once.

    How to debug, in short, go to your browser, inspect element, network tab, refresh, figure out which files are both registering the same element. Then check in the initiator to see which files are loading those files. Then you get a way better idea of why your app is not resolving the same import to a single place (your deduped dependency).

    One reason why you might face this problem is due to semver. If you have multiple different major versions of the same dependency, NPM cannot just dedupe all of the installations to your root node_modules. How you solve this is up to you. Some people use npm-aliases for their different majors of a dependency, some people implement a plugin in their build-tool to resolve paths to a single installation, etc.

    0 讨论(0)
  • 2020-12-17 21:35

    For those cases where it's a custom element you're registering simply check that an element by this name hasn't already been registered. Obviously you can include more complex logic to vary the name, decorate the class, etc, however this simply checks to see if something is already registered using the existing API and if not, registers the given thing (in my style--yours can vary, this is simply showing how to generally avoid the error):

    customElements.get('the-element') || customElements.define('the-element', HTMLTheElement);
    

    For more on the API see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry

    0 讨论(0)
提交回复
热议问题