Search code examples
sassthemessveltevitemixins

"Unused CSS selector" when using a SASS themify mixin with Svelte and Vite:


I'm trying to create a small web application using Svelte. One of the requirements is to be able to change the application "theme" on demand, for example - dark theme, light theme, high contrast, and so on.

I've been using an online mixin snippet to help me with that - https://medium.com/@dmitriy.borodiy/easy-color-theming-with-scss-bc38fd5734d1

However, this doesn't work consistently, and I often get errors like: [vite-plugin-svelte] /path/to/svelte/component.svelte:61:0 Unused CSS selector "main.default-theme div.some.element.identification" even tho the selector is used and is receiving it's non-themed attributes.

Inside a themes.scss file:

@mixin themify($themes) {

    @each $theme,
    $map in $themes {
        main.#{$theme}-theme & {
            $theme-map: () !global;

            @each $key,
            $submap in $map {
                $value: map-get(map-get($themes, $theme), '#{$key}');
                $theme-map: map-merge($theme-map, ($key: $value)) !global;
            }

            @content;
            $theme-map: null !global;
        }
    }
}

@function themed($key) {
    @return map-get($theme-map, $key);
}

$themes: (
    default: (
        strokeColor: green,
        fillColor: red,
    ),
);

and inside another scss file that is importing themes.scss:

div.some.element.identification {
    some-non-themed-attribute: some-value;

    @include themify($themes) {
        stroke: themed('strokeColor');
        fill: themed('fillColor');
    }
}

now the punchline - when using this methodology, some elements are receiving their appropriate themed attributes, and others dont. I am also seeing the following error: [vite-plugin-svelte] /path/to/svelte/component.svelte:61:0 Unused CSS selector "main.default-theme div.some.element.identification"

the issue doesn't seem to be in the css selectors - since the elements that dont receive the themed attributes, still receive the other non-themed attributes in the same css clause.

Two final observations -

  1. When I'm building the project (using vite build), I can see that the css asset file being created doesn't include the css selectors that are missing their themed attributes.
  2. When i'm using the devtools to locate the supposedly unused selectors (whose themed attributes are not present), they can be found - despite the error message.

I've been trying different way to solve this issue and nothing works consistently.

Thank you in advance for your help!


Solution

  • You could try checking these different items:

    • If you use svelte-preprocess, try to add scss: { prependData: `@import 'src/styles/theme.scss';` } or whatever the path to your theme is, to the config object.
    • If it still does not work, maybe try to swap svelte-preprocess with vite-preprocess
    • Disable any potential css purge plugin