⚡ Svelte: Export a class Property

Svelte

I recently started contributing to an Open Source Project, Immich, which uses a Svelte frontend. Svelte has been great to work with so far. I especially like the easy, intuitive way it handles binding properties and events for Svelte Components.

Props

For example, pass data to a component via a property:

<MyComponent enabled={true} />
// my-component.svelte
<script lang="ts">
  export let enabled: boolean;
</script>

{#if enabled}
 <span>I'm enabled! 😂</span>
{:else}
 <span>I'm not enabled. 😢</span>
{/if}

Problem

Eventually, I wanted to export a property called class, hoping to allow class names to pass through to the underlying element. Something like this:

<MyComponent class="custom-class" />
// my-component.svelte
<script lang="ts">
  export let class = '';
</script>

<span {class}>Hello</span>

Well, it turns out, as you might have guessed, export let class is invalid because class is a reserved word.

Solution

Luckily there is a solution to this, which takes advantage of an export alias. Basically this works just fine:

// my-component.svelte
<script lang="ts">
  let className = '';
  export { className as class }
</script>

 <span class={className}>Hello</span>
{/if}

So there you have it! A way to use the class prop, even though it is a reserved word in the language.