sveltejs - static properties on components

Viewed 798

I have a scenario where I need to provide information to a component class such that downstream instantiations can make use of that info.

For instance:

import { AComponent } from 'AComponent.svelte'
...
AComponent.classInfo = {something: somedata}

And then, the component could access that information as in:

<script>
  let something = AComponent.classInfo.something
</script>

There seemed to be some effort in providing this kind of functionality in V2 (I'm using 3) that was discussed in these issues: Support Component Static Method #480, which resulted in Added setup function which can supply static methods/properties. #572.

However, scanning the current docs reveals no such setup method. So, did this survive from V2 to 3 & if not, is there some way to do this?

2 Answers

You can define static properties that are not instance specific in the module script block

<script context="module">
  export const someValue = 123
</script>
<script>
  // Normal component stuff
</script>

and then import it directly from the component file:

import { someValue } from './MyComponent.svelte'

Note that this is a value shared among all instances of this component.

At least in version v3.32, it's not possible to define static properties in a Svelte Component. Only named exports are possible.

The only workaround I known is using a custom webpack loader/rollup plugin, and the implementation is never pretty.

Related