Skip to content

enhancement(custom element): make tag optional in customElement component options #12751

Closed
@Theo-Steiner

Description

@Theo-Steiner

Describe the problem

there are currently three possible options to set the tag name of a custom element in svelte

  1. As a string value set to customElement: <svelte:options customElement="my-element" />
  2. As a string value set to customElement.tag: <svelte:options customElement="{tag: 'my-element'}" />
  3. Not setting it at all using <svelte:options />, but instead using customElements.define('my-element', MyElement.element);

option 1 is for the most simple use cases, where you want svelte to handle everything for you, so that you just have to import the module and as a side effect your component is registered as a custom element with the tag of "my-element".


option 2 was introduced with svelte 4's custom elements rework (#8457) and is for more advanced use cases, where you perhaps might want to pass on shadow root creation or add type converters for props set via attributes

<svelte:options
	customElement={{
		tag: 'custom-element',
		shadow: 'none',
		props: {
			name: { reflect: true, type: 'Number', attribute: 'my-index' }
		},
	}}
/>

option 3 is used when you need more control over how your element is registered to the customElements registry. A common case for this is a scenario in which a website imports the svelte-built custom element from two sources. Since trying to register a custom element with a tag name that is already in the customElements registry fails (see: #7595), users have to check before defining the tag with the customElements registry.

if (!customElements.get(tag_name)) {
  customElements.define('my-element', MyElement.element);
}

given that some use cases require both advanced settings (as provided by option 2) and control over how customElements are registered (as provided option 3), it would be really nice if there were a way to combine the two options - allowing both fine grained control over the element that is being created and the way it is registered.

Describe the proposed solution

if tag were optional in the customElement config passed to svelte:options, the compiler could decide based on the existence of a tag name whether to add a call for registering the custom element.

<svelte:options
	customElement={{
		shadow: 'none',
		props: {
			name: { reflect: true, type: 'Number', attribute: 'my-index' }
		},
	}}
/>

↑ this svelte:option would create the custom element's class, but not call customElements.define

Importance

nice to have

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions