2

How to know the name of a Svelte component from inside?

Somewhere in .svelte file:

    <script>
    console.log('name of this component is', ...)
    </script>

What's instead of the ellipsis?

geometer
  • 61
  • 2

1 Answers1

1

You can give Svelte components a name by using the module context script:

<script context="module">
  const name = 'whatever you want';
</script>

<script>
  console.log('name of this component is', name);
</script>

Code inside <script context="module"> is run once and exists outside of the livecycle of the components. More in the docs: https://svelte.dev/docs#script_context_module

Is there another way? Svelte components are compiled to classes, but you don't have access to them (without crude, brittle hacks). Moreoever classes do not have a stable way to get their name. There's constructor.name, but that name could change when you minify your code (more on this here: How to get a JavaScript object's class?). So the method above is the most consistent and "svelte" way to do this.

dummdidumm
  • 4,828
  • 15
  • 26
  • 2
    As a bonus to this, the importer can easily rename your component by doing `import ThatComponent from './ThisComponent.svelte'` so there is not even a way of knowing what they used. – Stephane Vanraes Sep 17 '21 at 10:31