How to disable Svelte warning "Unused CSS selector"
Asked Answered
S

5

30

The approach of my graphic designer for formatting our Svelte application is having a systematic set of classes in LESS, importing the appropriate LESS file in the component or page, and then applying those classes wherever he needs them. As a result we have an abundant amount of unused classes, which we might use at a later point.

The great thing about Svelte is that unused CSS is not compiled, so all those (yet) redundant classes are not in the way anyway. However, whenever we compile, we get a big list of warnings: "Unused CSS selector". This is a major nuisance, because it makes it harder to notice when an actual error is created. Plus it just looks ugly.

I checked the documentation and there is a way to suppress warnings, but that only works for the HTML part.

Is there any way of getting rid of these warnings? Note that we use Svelte Preprocess.

Stooge answered 13/3, 2020 at 22:4 Comment(1)
github.com/sveltejs/svelte/issues/1594Nummular
C
4

You gotta get the compiler not to barf, and also get VSCode not to shout at you.

Workspace-level VSCode Settings

  "svelte.plugin.svelte.compilerWarnings": {
    "css-unused-selector": "ignore",
  }

sveltekit.config.ts

import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/kit/vite';

/** @type {import('@sveltejs/kit').Config} */
const config = {
    // Consult https://kit.svelte.dev/docs/integrations#preprocessors
    // for more information about preprocessors
    preprocess: vitePreprocess(),
    onwarn: (warning, handler) => {
        if (warning.code === 'css-unused-selector') {
            return;
        }
        handler(warning);
    },
    kit: {
        // adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
        // If your environment is not supported or you settled on a specific environment, switch out the adapter.
        // See https://kit.svelte.dev/docs/adapters for more information about adapters.
        adapter: adapter()
    },
    preprocess: vitePreprocess()
};

export default config;

Source: https://github.com/sveltejs/language-tools/issues/650#issuecomment-1729917996

Contra answered 14/10, 2023 at 3:49 Comment(2)
You also have a duplicate preprocess key in your config.Leaseholder
To add: catching the text (/ message) contained in the CLI output use warning.message.startsWith('text').Leaseholder
R
31

I found this solution a bit smoother which I modified slightly:

// rollup.config.js
...
svelte({
    ...
    onwarn: (warning, handler) => {
        const { code, frame } = warning;
        if (code === "css-unused-selector")
            return;

        handler(warning);
    },
    ...
}),
...
Rossetti answered 15/4, 2020 at 21:23 Comment(3)
Just want to mention, this works in SvelteKit the same: add the onWarn function to the "config" object root in svelte.config.jsManufactory
If you use svelte as a vite plugin, this goes into vite.config.jsSeafood
i think you should make a full answer how to make it with vite or sveltekitArboreal
C
4

You gotta get the compiler not to barf, and also get VSCode not to shout at you.

Workspace-level VSCode Settings

  "svelte.plugin.svelte.compilerWarnings": {
    "css-unused-selector": "ignore",
  }

sveltekit.config.ts

import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/kit/vite';

/** @type {import('@sveltejs/kit').Config} */
const config = {
    // Consult https://kit.svelte.dev/docs/integrations#preprocessors
    // for more information about preprocessors
    preprocess: vitePreprocess(),
    onwarn: (warning, handler) => {
        if (warning.code === 'css-unused-selector') {
            return;
        }
        handler(warning);
    },
    kit: {
        // adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
        // If your environment is not supported or you settled on a specific environment, switch out the adapter.
        // See https://kit.svelte.dev/docs/adapters for more information about adapters.
        adapter: adapter()
    },
    preprocess: vitePreprocess()
};

export default config;

Source: https://github.com/sveltejs/language-tools/issues/650#issuecomment-1729917996

Contra answered 14/10, 2023 at 3:49 Comment(2)
You also have a duplicate preprocess key in your config.Leaseholder
To add: catching the text (/ message) contained in the CLI output use warning.message.startsWith('text').Leaseholder
Y
3

I use a simple explicit ignore mechanism:

First, define the warning key and a regex to capture the meat of the ignore message. Then, loop over ignore patterns and match at least one.

// rollup.config.js
...
const warnIgnores = {
  'css-unused-selector': {
    capture: /.*"(.*)"$/,
    ignore: [
      /^\.p\d+/,
      /^\.sm\d+/,
      /^\.md\d+/,
      /^\.lg\d+/,
      /^\.xg\d+/,
      /^\.all\d+/,
      /^\.row(::after)?/
    ]
  }
}
...
svelte({
  ...
  // Explicitely ignore warnings
  onwarn: (warning, handler) => {
    const { message, code } = warning;
    const patterns = warnIgnores[code];
    if (patterns != undefined) {
      /* Find the meat. */
      const meat = message.match(patterns.capture);
      if (meat != null) {
        for (var i = 0; i < patterns.ignore.length; i++) {
          if (meat[1].match(patterns.ignore[i]) != null) {
            return;
          }
        }
      }
    }
    handler(warning);
  },
  ...
});

Explicit is better than implicit!

Yoon answered 10/8, 2021 at 11:13 Comment(3)
Do you perhaps know how to write this kind of conditional ignoring, but to have it apply only to imported files? I would like to keep the warnings of unused selectors that come from the same component, but if I for example import my _forms.scss and not use one of the many form elements from it, then seeing the warning is absurd, and those are the ones I would want to ignore.Trommel
Not sure, but please do a console.log on message and loop for the file name. If found, modify the code to extract the filename by regex and predict it.Yoon
as of 2024, vite 5 and sveltekit 5 - it doesn't work. Code runs, but the css-unused-selector is never raised. also had to configure it in vite.config.js, defineConfig.build.rollupOptions.onwarnCribwork
C
1

No need to create a rollup.config.js file, just configure it vite.config.js:

import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vitest/config';

export default defineConfig({
    plugins: [sveltekit()],
    build: {
        rollupOptions: {
            onwarn: (warning, handler) => {
                const { code, frame } = warning;
                if (code === "anchor-is-valid" || code === "a11y-autofocus") {
                    return;
                }
                if (code === "css-unused-selector" && frame && frame.includes("shape")) {
                    return;
                }
                handler(warning);
            }
        }
    },
    test: {
        include: ['src/**/*.{test,spec}.{js,ts}']
    }
});
Chromogen answered 14/9, 2023 at 19:22 Comment(0)
S
0

There doesn't seem to be any possibility to turn off this warning in a proper way. However, there is a workaround.

In node_modules/svelte/compiler.js, remove line 24842 or put it in comments:

this.stylesheet.warn_on_unused_selectors(this);

You will have to do this again when you update or reinstall svelte.

Stooge answered 17/3, 2020 at 10:49 Comment(3)
This is the only way that actually addresses the issue, for me (which was the massive performance hit that I get because it's generating 1000s of warnings per file, VSCode stops autocompleting or formatting my code on save, system locks to a halt, etc). Thank youLibna
You're welcome, but...check the other answer, by Fractalf. If you use Rollup, you can just take over his code suggestion for in the config file.Stooge
Yeah I am using rollup and tried that method. Didn't work for me. Performance was still bad.Libna

© 2022 - 2024 — McMap. All rights reserved.