Can I keep "unused css selector"?

Viewed 1570

I noticed that svelte will purge my css automatically, all "unused css selector" will get removed.

For example:

<p class="blue">This is a paragraph.</p>

<style>
    .red{
        color: red;
    }
    .blue{
        color: blue;
    }
</style>

The style for class 'red' will be removed. How can I keep the '.blue' selector? I want to use it later at some point.

4 Answers

You can also use global in the style tag, if you have svelte-preprocess installed (link):

<style global>
    .red{
        color: red;
    }
    .blue{
        color: blue;
    }
</style>

You probably want to wrap the selector in :global(...), like

:global(.red) {
    color: red;
}

This forces Svelte to keep the class around, and also makes it so the selector isn't scoped to that single component. This is usually what you want when Svelte is removing selectors that you want to keep.

If you're using Sveltekit, you can create a app.css (or scss) file and import it into your main __layout.svelte file.

import '../app.scss';

If you're not using sveltekit, you can edit the global.css file found in public/global.css

This guide explains the Sveltekit version in more detail

I tried :global(), <style global> and @import but nothing worked. My case was something like this:

<ul>
    {#each items as item}
        <li class="method–{item.method}">{item.text}</li>
    {/each}
</ul>

I finally found a solution that worked:

<li class="{'method-' + item.method}">

Makes no difference in the output but somehow doesn't trigger the CSS purging. Really annoying to have to deal with awkward tooling bugs.

Related