如何在 Svelte 中使用 Web 组件?

How to use web components in Svelte?

我想使用 https://github.com/microsoft/vscode-webview-ui-toolkit 中的几个 Web 组件。但是我不知道如何在 Svelte 中使用它们,因为 svelte 将 Web 组件视为 svelte 组件。

当我尝试使用它们时,

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

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

我收到这个错误,

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)

Button 是自定义元素 class,不应像 Svelte 组件那样使用。您需要改用自定义元素标签,在本例中为 <vscode-button>.

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

您可能需要进行其他设置才能初始化 Web 组件 - 我不熟悉此库。