user11953615
user11953615

Reputation: 47

How can I change the class name of a svelte component?

I've got multiple files named the same thing, but coming from totally different locations. Here's a simplified example:

AdminViews/Item.svelte
ClientViews/Item.svelte
DefaultViews/Item.svelte

I try to import them all from within the same file, like so:

import AdminItem from 'AdminViews/Item.svelte';
import ClientItem from 'ClientViews/Item.svelte';
import DefaultItem from 'DefaultViews/Item.svelte';

Even though I'm importing them as different names, they all reference whichever one is imported last. After investigating, it looks like this is because svelte sets the class name to whatever the filename is, regardless of path, e.g.:

class Item extends _internal.SvelteComponentDev {

It's identical for all of them, so when they're imported they each override the one above.

So my question is: how do I fix this collision without changing the filenames? Surely there's a way to change the class name of the component, I just can't find it in the docs.

If there isn't a way to fix it, then how does svelte deal with the fact that people often re-use common names, like utils or index?

Upvotes: 4

Views: 1815

Answers (1)

Rich Harris
Rich Harris

Reputation: 29585

Using the Svelte compiler directly, you can pass in whatever name you like:

const compiled = svelte.compile(code, {
  name: 'Potato'
});

Unfortunately, most of the time you interact with the compiler indirectly, via something like rollup-plugin-svelte or svelte-loader. Currently, those plugins don't offer a way to control the name of each component — ideally they would let you specify a filename => name function that overrode the default behaviour if it returned anything. (This might be worth opening an issue, if you're so inclined).

For filenames like src/Thingamajig/index.svelte, the index is already removed in favour of Thingamajig. Other clashes don't matter as far as Svelte is concerned, because the names are in separate modules — it's the bundler's job to make sure that Item, Item and Item don't trip over each other's toes in the output.

Upvotes: 5

Related Questions