'How can eslint be configured to work with svelte and postcss-nesting?

Using postcss with plugin postcss-nesting in svelte is quite easy -- adding postcss-nesting to the preprocess config in svelte.config.js is the only thing needed:

import preprocess from "svelte-preprocess";
import postcssNesting from "postcss-nesting";

const config = {
    preprocess: preprocess({
        postcss: {
            plugins: [
                postcssNesting()
            ]
        }
    }),
    // ...
};

export default config;

Now I can define nested CSS using the "&" syntax.
For example, when I have this in an example.svelte file:

<div class="example">
    One <span class="nested">two</span> three
</div>

<style lang="postcss">
    .example {
        color: red;
        & .nested {
            text-decoration: underline;
        }
    }
</style>

However, I was not able to find a way that eslint does accept it. It reports that an identifier is expected after the & character.



Solution 1:[1]

I had the same problem with postcss-nested when added postcss as npx script npx svelte-add@latest postcss. Adding postcss manually and setting postcss plugins in rollup.config.js like described in svelte-preprocess documentation instead of npx variant however works well.

  1. Install dependencies npm i postcss postcss-nested -D
  2. Replace preprocess: sveltePreprocess({ sourceMap: !production }), line with
    preprocess: sveltePreprocess({ 
     sourceMap: !production,
     postcss: {
         plugins: [
             require('postcss-nested')()
         ]
     }
    }),
    

Solution 2:[2]

No, it doesn't "work", but using the svelte3/ignore-styles setting you're able to use ESLint for the remaining <script> and html sections.

// eslint.config.js

  rules: {
    ...
  },
  settings: {
    'svelte3/ignore-styles': () => false,
    ...

Ignoring styles is the default when the <style> contains a lang= or type= attribute since eslint-plugin-svelte3 v3.3.0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexander Christophorov
Solution 2