poppa / sveltekit-svg

SvelteKit plugin that makes it possible to import SVG files as Svelte components, inline SVG code or urls
MIT License
234 stars 23 forks source link

PSA: css selectors that target an imported `.svg` are considered `unused` and are pruned #51

Closed ar-rm closed 1 year ago

ar-rm commented 1 year ago

Hi,

Thank you for this great plugin. It's nice to be able to import the raw svg xml and seamlessly pass attributes into it at the same time.

This video provided a nice overview and use case: LIVE Coding & Chill: 🖼 importing SVGs in SvelteKit 🌠


Here's what I ran into:

When using import for an .svg, css selectors, that target only that svg, are pruned because Svelte (or Vite or one of the css minifiers) thinks they're unused.

Example:

<script>
    import Logo from '$lib/logo.svg?component';
</script>

<Logo id="logo"/>

<style>
#logo {
    opacity: 0.5;
}
</style>

Result:

The same happens if you explicitly set the id= inside of the original .svg file, as opposed to setting it via an attribute on the sveltekit-svg created <Logo id="logo"/> tag.

I originally found this with a <style lang="sass"> block. I thought maybe this had something to do with using sass as a pre-processor. But it doesn't. At least not in this case.

But if you copy/paste the .svg code directly into the .svelte file, it works as expected:

<svg id="logo"/>

<style>
#logo {
    opacity: 0.5;
}
</style>

Result:


Workarounds:

<div id="logo">
    <Logo>
</div>

<style>
#logo svg {
    opacity: 0.5;
}
</style>

Here's some commentary about this exact issues: https://github.com/sveltejs/svelte/issues/5804

This seems to bite a lot of people. It's the second or third issue I've run into related to import (which seems to be the frequently preferred method of using assets) and then later having issues because some other plugin or generic code doesn't recognizing that dynamic import at compile-time.

I'm posted this not because it's a bug with sveltekit-svg, but more for:

I have no grand suggestion or request, since this seems to have basically everything to do with how SvelteKit is setup and not your plugin :-)

I hope this helps.

Thanks.

poppa commented 1 year ago

Thanks for your effort, it's appreciated 😍

As you say, this is how Svelte works. Newcomers may have difficulties differentiating DOM nodes from Svelte components, and think they'd behave the same, but they obviously don't. But this is again not very different from React or any other component based framework.