Reputation: 81
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?
Upvotes: 3
Views: 2234
Reputation: 5426
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.
Upvotes: 2