How to use web components in Svelte?
Asked Answered
E

1

6

I want to use few web components from https://github.com/microsoft/vscode-webview-ui-toolkit. But I don't know to how to use them in Svelte as svelte treats the web components as svelte components.

When I try to use them as,

<script lang="ts">
import { Button } from "@vscode/webview-ui-toolkit"
</script>

<main>
  <Button appearance="primary">Text</Button>
</main>

I get this error,

Element does not support attributes because type definitions are missing for this Svelte Component or element cannot be used as such.

Underlying error:
JSX element class does not support attributes because it does not have a '$$prop_def' property.ts(2607)
'Button' cannot be used as a JSX component.
  Its instance type 'Button' is not a valid JSX element.
    Property '$$prop_def' is missing in type 'Button' but required in type 'ElementClass'.

Possible causes:
- You use the instance type of a component where you should use the constructor type
- Type definitions are missing for this Svelte Component. If you are using Svelte 3.31+, use SvelteComponentTyped to add a definition:
  import type { SvelteComponentTyped } from "svelte";
  class ComponentName extends SvelteComponentTyped<{propertyName: string;}> {}ts(2786)
Echeverria answered 1/3, 2022 at 5:44 Comment(1)
Have you tried to write a test for you custom button on the svelte component?Intendment
C
8

Button is a custom element class, and should not be used like a Svelte component. You need to use the custom element tag instead, which in this case is <vscode-button>.

<main>
  <vscode-button appearance="primary">Text</vscode-button>
</main>

There may be additional setup you have to do to initialize the web components - I'm not familiar with this library.

Chemical answered 3/3, 2022 at 16:5 Comment(1)
The rest of the step is documented here: github.com/sveltejs/svelte/issues/7334Echeverria

© 2022 - 2024 — McMap. All rights reserved.