Skip to content

Custom Elements built with Svelte 4 do not work in Home Assistant #8954

Closed
@VS-X

Description

@VS-X

Describe the bug

Context: Home Assistant's entire frontend is composed of custom elements. All the built-in ones are written in Lit. One can create a custom dashboard card by adding a new resource, which consists of a JS file containing a custom element. For the custom element card to render, it has to export setConfig function.

When a custom element is rendered, Home Assistant calls setConfig on each such element in _createElement. Here's an extract:

const element = document.createElement(tag) 
element.setConfig(config);

A custom element built with Svelte 3 works when added to Home Assistant, but Svelte 4's doesn't because of: TypeError: element.setConfig is not a function.
Is the exported function not immediately available when the component is created?

Reproduction

Reproduction is a bit time-consuming, since you need to have a Home Assistant environment running.

  1. Create a new Vite + Svelte 4 project (npm init vite)
  2. Add a tag and the corresponding build option: <svelte:options customElement="svelte-component" />
  3. Add exported function setConfig to the component
  4. Run npm run build
  5. Add a built .js file as a new dashboard resource in Home Assistant
  6. Add a new custom card to the dashboard

Here is an example component with the exported setConfig:

<svelte:options customElement="svelte-card" />

<script>
  export let hass;
  let config = {}

  export function setConfig (conf = {}) {
    console.log('setConfig')
    config = { ...conf }
  }
</script>

<main>
  test
</main>

And here is main.ts:

// also tried export {default as default} from './App.svelte'
export * from './App.svelte'

It starts to work if you downgrade Svelte from 4 to 3 and re-build.

Logs

No response

System Info

System:
    OS: macOS 13.4.1
    CPU: (10) arm64 Apple M1 Pro
    Memory: 39.09 MB / 32.00 GB
    Shell: 3.6.1 - /opt/homebrew/bin/fish
  Binaries:
    Node: 18.13.0 - ~/.local/state/fnm_multishells/11850_1688733464692/bin/node
    npm: 8.19.3 - ~/.local/state/fnm_multishells/11850_1688733464692/bin/npm
  Browsers:
    Safari: 16.5.1
  npmPackages:
    svelte: ^4.0.5 => 4.0.5

Severity

blocking an upgrade

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions