Open-Source Wikis

/

Svelte

/

Features

/

Custom elements

sveltejs/svelte

Custom elements

Active contributors: Rich Harris, Simon H

Purpose

A Svelte component can be compiled into a standards-compliant Custom Element by setting <svelte:options customElement="my-tag"> (or customElement: 'my-tag' in the compile options). The component is wrapped in an HTMLElement subclass that handles attribute reflection, slot projection, and lifecycle adaptation.

User docs: https://svelte.dev/docs/svelte/custom-elements.

Implementation

packages/svelte/src/internal/client/dom/elements/custom-element.js (~10 KB) is the runtime adapter. It defines a class that extends HTMLElement and:

  • Reads observed attributes from the component's $props shape.
  • Reflects attribute changes into a Source that the inner Svelte component reads.
  • Projects child nodes into the host's <slot> mapping.
  • Calls mount on connectedCallback, unmount on disconnectedCallback.
  • Exposes $host() (the $host rune) so component code can dispatch events on the host node.

The compiler emits customElement(...) from internal/client/index.js (re-exporting from this module) when compile_options.customElement is truthy.

$host rune

$host() returns the host element of a custom-element-compiled component. The compiler emits a reference to component_context.x.h (a host pointer set by the custom-element wrapper). The visitor lives in packages/svelte/src/compiler/phases/3-transform/client/visitors/Identifier.js.

Server behaviour

On the server, custom-element components render plain HTML (no host element wrapper). The customElement flag is mostly a client-side concern.

Tests

  • packages/svelte/tests/runtime-browser/ runs Playwright Chromium and exercises custom-element-compiled components in a real DOM.
  • Compile-time options validation lives in packages/svelte/tests/validator/.

Key source files

File Purpose
packages/svelte/src/internal/client/dom/elements/custom-element.js The HTMLElement subclass and lifecycle adapter.
packages/svelte/src/compiler/validate-options.js customElement option schema.
packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteOptions.js <svelte:options customElement> parsing.

Entry points for modification

Most evolution happens in internal/client/dom/elements/custom-element.js. To change the customElement option schema (e.g., add a new lifecycle hook), edit validate-options.js and the matching emit in the SvelteOptions visitor.

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

Custom elements – Svelte wiki | Factory