eslint-plugin-svelte: Linting with flat config (ESLint 9) does not work with TypeScript

Before You File a Bug Report Please Confirm You Have Done The Following…

  • I have tried restarting my IDE and the issue persists.
  • I have updated to the latest version of the packages.

What version of ESLint are you using?

9.0.0

What version of eslint-plugin-svelte are you using?

2.36.0

What did you do?

Configuration
import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
import eslintPluginSvelte from 'eslint-plugin-svelte';

export default [
  { ignores: ['.svelte-kit'] },
  { languageOptions: { globals: globals.browser } },
  pluginJs.configs.recommended,
  ...tseslint.configs.recommended,
  ...eslintPluginSvelte.configs['flat/recommended'],
];
<script lang="ts">
	let count: number = 0;
</script>

{count}

What did you expect to happen?

The linter to be happy

What actually happened?

 2:11  error  Parsing error: Unexpected token :

Link to GitHub Repo with Minimal Reproducible Example

https://github.com/MathiasWP/eslint-9-svelte-typescript-error

Additional comments

No response

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 11
  • Comments: 36 (4 by maintainers)

Commits related to this issue

Most upvoted comments

For completeness, here is a full eslint “flat file” configuration that works for Svelte projects that use TypeScript. It also includes Prettier linting.

Maybe an example of such a “flat file” config could be added to the doc of eslint-plugin-svelte, because so far there are only examples of the “old” type of config file (if I’m not mistaken).

// eslint.config.cjs

import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
import eslintPluginSvelte from 'eslint-plugin-svelte';
import js from '@eslint/js';
import svelteParser from 'svelte-eslint-parser';
import tsEslint from 'typescript-eslint';
import tsParser from '@typescript-eslint/parser';

export default [
  js.configs.recommended,
  ...tsEslint.configs.strict,
  ...eslintPluginSvelte.configs['flat/recommended'],
  eslintPluginPrettierRecommended, // must be last to override conflicting rules.
  {
    rules: {
      semi: ['warn', 'always'],
      quotes: [
        'warn',
        'single',
        { avoidEscape: true, allowTemplateLiterals: true },
      ],
      'no-nested-ternary': 'error',
      'linebreak-style': ['error', 'unix'],
      'no-cond-assign': ['error', 'always'],
      'no-console': 'error',
      '@typescript-eslint/sort-type-constituents': 'error',
      'sort-imports': [
        'error',
        {
          ignoreCase: true,
          ignoreDeclarationSort: false,
          ignoreMemberSort: false,
          memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'],
          allowSeparatedGroups: true,
        },
      ],
    },
  },
  {
    files: ['**/*.svelte'],
    languageOptions: {
      parser: svelteParser,
      parserOptions: {
        parser: tsParser,
      },
    },
    rules: {
      'svelte/no-target-blank': 'error',
      'svelte/no-at-debug-tags': 'error',
      'svelte/no-reactive-functions': 'error',
      'svelte/no-reactive-literals': 'error',
    },
  },
];

Something to note that I haven’t see mentioned yet, typescript-eslint version 8 added stable support for projectService that replaces project:

 parserOptions: {
-        project: true,
+        projectService: true,

The biggest new feature added in this version is the stability of our new “project service”. In short, the project service is a new way to enable typed linting that is generally easier to configure and faster at runtime than our previous offerings.

The project service will automatically find the closest tsconfig.json for each file (like project: true). It also allows enabling typed linting for files not explicitly included in a tsconfig.json. This should remove the need for custom tsconfig.eslint.json files to lint files like eslint.config.js!

Internally, the project service uses the same TypeScript APIs that editors such as VS Code use. Doing so should make it harder to accidentally configure different type information for ESLint than what you see in day-to-day editing.

I think that it helps you to specify files for each config object like below:

import globals from 'globals';
import js from '@eslint/js';
import tseslint from 'typescript-eslint' // v7
import prettierConfig from 'eslint-config-prettier';
import svelte from 'eslint-plugin-svelte';
import svelteParser from 'svelte-eslint-parser';

/** @type {import('typescript-eslint').Config} */
export default = [
  ...[
    js.configs.recommended,
    ...tseslint.configs.strictTypeChecked, // typescript-eslint set `['**/*.ts', '**/*.tsx', '**/*.mts', '**/*.cts']` to `files`
    prettierConfig,  // eslint-config-prettier does not turn 'svelte/*' rules off
    { // overrides options should be after other config
      languageOptions: {
        parser: tseslint.parser,
        parserOptions: {
          sourceType: 'module',
          extraFileExtensions: ['.svelte']
        },
        globals: { ...globals.browser, ...globals.node },
      },
      rules: { /* rules for js/ts/svelte */ } // don't set 'svelte/*' rules here
    }
  ].map(conf => ({ ...conf, files: ['**/*.js', '**/*.ts', '**/*.svelte'] })), // To override `files` is so important!!
  ...svelte.configs['flat/recommended'], // eslint-plugin-svelte set `['*.svelte', '**/*.svelte']` to `files`
  ...svelte.configs['flat/prettier'], // if non svelte files occur 'svelte/*' error, these element should be set `files`
  { // your config should be after
    files: ['*.svelte', '**/*.svelte'], // the same value as eslint-plugin-svelte `files` option
    languageOptions: {
      parser: svelteParser,
      parserOptions: { parser: tseslint.parser }
    },
    // ↓ rule types;  sveltejs/eslint-plugin-svelte #735 
    /** @type {import('eslint').Linter.RulesRecord} */
    rules: { /* rules for svelte */ }
  },
  {
    // other override settings. e.g. for `files: ['**/*.test.*']`
  },
  { ignores: ['node_modules/', /* other ignores */] } // overrides global ignores
];

It because that typescript-eslint set ['**/*.ts', '**/*.tsx', '**/*.mts', '**/*.cts'] to files.

[!NOTE] '**/*.js' pattern may be not overridden with '*.js' pattern.

Using typescript-eslint helper function config(...) as below provides the almost same flat-config array as above.

eslint.config.js using `config` helper
import globals from 'globals';
import js from '@eslint/js';
import tseslint from 'typescript-eslint' // v7
import prettierConfig from 'eslint-config-prettier';
import svelte from 'eslint-plugin-svelte';
import svelteParser from 'svelte-eslint-parser';

const defaultConfig = tseslint.config({
  files: ['**/*.js', '**/*.ts', '**/*.svelte'],
  extends: [
    js.configs.recommended, // if it occurs a type error, you can install `@types/eslint__js` package
    ...tseslint.configs.strictTypeChecked,
    prettierConfig // if it occurs a type error, you can install `@types/eslint-config-prettier` package
  ],
  languageOptions: {
    parser: tseslint.parser,
    parserOptions: {
      sourceType: 'module',
      extraFileExtensions: ['.svelte']
    },
    globals: { ...globals.browser, ...globals.node },
  },
  rules: { /* rules for js/ts/svelte */ } // don't set 'svelte/*' rules here
});

const svelteConfig = tseslint.config({
  extends: [
    ...svelte.configs['flat/recommended'],
    ...svelte.configs['flat/prettier']
  ],
  languageOptions: {
    parser: svelteParser,
    parserOptions: { parser: tseslint.parser }
  },
  // ↓ rule types;  sveltejs/eslint-plugin-svelte #735 
  /** @type {import('eslint').Linter.RulesRecord} */
  rules: { /* rules for svelte */ }
});

/** @type {import('@typescript-eslint/utils').TSESLint.FlatConfig.ConfigArray} */
export default = [
  ...defaultConfig,
  ...svelteConfig,
  {
    // other override settings. e.g. for `files: ['**/*.test.*']`
  },
  { ignores: ['node_modules/', /* other ignores */] } // overrides global ignores
];

This should be added to the readme in the parser configuration section. We also don’t have to import the ts parser see here https://typescript-eslint.io/packages/typescript-eslint/#manually-configuring-our-plugin-and-parser.

@falco467 Thanks for the suggestion! Setting programs to false seems to fix the issue I was running into. I tested various rules in .js, .ts, and .svelte files and all rules are working, including the type checked rules.

eslint.config.js
import js from '@eslint/js';
import ts from 'typescript-eslint';
import prettier from 'eslint-config-prettier';
import svelte from 'eslint-plugin-svelte';
import globals from 'globals';

const tsConfig = ts.config({
    files: ['**/*.js', '**/*.ts', '**/*.svelte'],
    extends: [
  	  js.configs.recommended,
  	  ...ts.configs.strictTypeChecked,
  	  ...ts.configs.stylisticTypeChecked,
  	  prettier
    ],
    languageOptions: {
  	  globals: {
  		  ...globals.browser,
  		  ...globals.nodeBuiltin
  	  },
  	  parserOptions: {
  		  project: './tsconfig.eslint.json',
  		  tsconfigRootDir: import.meta.dirname,
  		  extraFileExtensions: ['.svelte'],
  		  programs: false
  	  }
    }
});

const svelteConfig = ts.config({
    files: ['**/*.svelte'],
    extends: [...svelte.configs['flat/recommended'], ...svelte.configs['flat/prettier']],
    languageOptions: {
  	  parserOptions: {
  		  parser: ts.parser
  	  }
    }
});

export default ts.config(...tsConfig, ...svelteConfig, {
    ignores: ['.svelte-kit/']
});

@MathiasWP : I had the same problem as you, but I got it working by adding files: ["**/*.svelte"], to the configuration object block that contains languageOptions.

My understanding, is that by adding files: ["**/*.svelte"], into this object, you tell it that this override will only apply to .svelte files.

    {
        files: ["**/*.svelte"],
        languageOptions: {
            ecmaVersion: 2022,
            sourceType: "module",
            parser: svelteParser,
            parserOptions: {
                parser: tsParser,
                extraFileExtensions: [".svelte"],
            },
        },
    },

I am not sure what the extraFileExtensions: [".svelte"], is supposed to do? It seem that I can remove it without any ill effect. Hope this helps.

Thank you so much! This solved the issue for me! 🎉

Hey, I had it working with the following config:

import js from "@eslint/js";
import eslintConfigPrettier from "eslint-config-prettier";
import eslintPluginSvelte from "eslint-plugin-svelte";
import globals from "globals";
import svelteParser from "svelte-eslint-parser";
import tsEslint from "typescript-eslint";

export default tsEslint.config(
  js.configs.recommended,
  ...tsEslint.configs.recommended,
  ...eslintPluginSvelte.configs["flat/recommended"],
  eslintConfigPrettier,
  ...eslintPluginSvelte.configs["flat/prettier"],
  {
    languageOptions: {
      ecmaVersion: 2022,
      sourceType: "module",
      globals: { ...globals.node, ...globals.browser },
      parser: svelteParser,
      parserOptions: {
        parser: tsEslint.parser,
        extraFileExtensions: [".svelte"],
      },
    },
  },
  {
    ignores: [
      "**/.svelte-kit",
      "**/.vercel",
      "**/.yarn",
      "**/build",
      "**/node_modules",
      "**/package",
    ],
  },
);

Hope it helps

Edit: updated with better imports and ignores

That’s what works for me:

"@eslint/js": "^9.8.0",
"typescript-eslint": "^8.0.0",
"eslint-plugin-svelte": "^2.43.0",
import js from "@eslint/js";
import ts from "typescript-eslint";
import svelte from "eslint-plugin-svelte";
import svelte_config from "./svelte.config.js";

/** @type {import("eslint").Linter.Config[]} */
export default [
    // js
    js.configs.recommended,
    // ts
    ...ts.configs.recommendedTypeChecked,
    ...ts.configs.strictTypeChecked,
    ...ts.configs.stylisticTypeChecked,
    // ts config
    {
        rules: {
            // ...
        },
    },
    {
        languageOptions: {
            parserOptions: {
                projectService: true,
                tsconfigRootDir: import.meta.dirname,
            },
        },
    },
    // other plugins
    // ...
    // svelte
    ...svelte.configs["flat/recommended"],
    // svelte config
    {
        rules: {
            // ...
        },
    },
    {
        files: ["**/*.svelte"],
        languageOptions: {
            parserOptions: {
                extraFileExtensions: [".svelte"],
                parser: ts.parser,
                svelteConfig: svelte_config,
            },
        },
    },
    // prettier
    prettier
    ...svelte.configs["flat/prettier"],
    // other
    {
        languageOptions: {
            globals: {
                ...globals.browser,
                ...globals.node,
            },
        },
        ignores: ["build/", ".svelte-kit/"],
    },
];

@kkirkfield

  1. I’m using typescript-eslint v8-alpha
  2. I was under the impression that settings programs to some value will in fact parse/lint all code delivered by that program and ignore the extraFileExtensions. I assumed they are only needed when programs is null/false.
  3. Setting programs to false seems to work for me - .svelte files are parsed and typescript rule violations seem to be reported on first glance. But maybe it is only working superficially - I’m looking forward to your report on this.

@kkirkfield It seems to work when I add programs: false to the parserOptions of the typescript-eslint block.

While the provided configs work for the simple recommended ruleset I cannot get it to work with the actual type-checking configs of typescript-eslint. To enable actual type-parsing, we need to enable the project: true parser option. And as soon as that is enabled, the error reads:

Parsing error: “parserOptions.programs” has been provided for @typescript-eslint/parser. The file was not found in any of the provided program instance(s): src\drehscheibe.svelte

import epSvelte from 'eslint-plugin-svelte'
import svelteParser from 'svelte-eslint-parser'
import tsEslint from 'typescript-eslint'

export default [
  ...tsEslint.configs.strictTypeChecked,
  ...epSvelte.configs['flat/recommended'],
  {
    languageOptions: {
      parser: tsEslint.parser,
      parserOptions: {
        project: true, // This line breaks the config (even with the other configs) - but it is needed for type-checking.
      },
    },
  },
  {
    files: ['**/*.svelte'],
    languageOptions: {
      parser: svelteParser,
      parserOptions: {
        parser: tsEslint.parser,
      }
    },
  },
]

And the inclusion of extra-file extensions doesn’t make a difference. Also including the project: true in both parserOptions doesn’t change anything. JS/TS Files get handled correctly, but svelte files are not recognized as soon as “project” is set to anything.

Thanks for all your comments! I still don’t know the best practices for integrating with typescript-eslint, but using typescript-eslint@v8-beta might work. https://x.com/tseslint/status/1795205941647884611

Did you look at the one I posted above (hidden in a details tag)? It continues to work, and I’ve upgraded since I posted to every single more recent release.

The primary difference I see is I am not using the pre-release alpha, but the stable release:

		"@typescript-eslint/eslint-plugin": "^7.11.0",

I haven’t been able to get any of the above configs working with eslint 9.3.0 and typescript-eslint 8.0.0-alpha.20 for .svelte files but it does work for all .js and .ts files.

From https://github.com/typescript-eslint/typescript-eslint/issues/8211:

Note that we do not plan on backporting ESLint v9 support to v7 versions of typescript-eslint. There are a lot of breaking changes inherent to our ESLint v9 support.

The error I’m seeing on .svelte files is: 0:0 error Parsing error: "parserOptions.programs" has been provided for @typescript-eslint/parser. The file was not found in any of the provided program instance(s): src\routes\+page.svelte

Here is an example config that is getting this error.

eslint.config.js

import js from '@eslint/js';
import ts from 'typescript-eslint';
import prettier from 'eslint-config-prettier';
import svelte from 'eslint-plugin-svelte';
import globals from 'globals';

const tsConfig = ts.config({
	files: ['**/*.js', '**/*.ts', '**/*.svelte'],
	extends: [
		js.configs.recommended,
		...ts.configs.strictTypeChecked,
		...ts.configs.stylisticTypeChecked,
		prettier
	],
	languageOptions: {
		globals: {
			...globals.browser,
			...globals.nodeBuiltin
		},
		parserOptions: {
			project: './tsconfig.eslint.json',
			tsconfigRootDir: import.meta.dirname,
			extraFileExtensions: ['.svelte']
		}
	}
});

const svelteConfig = ts.config({
	files: ['**/*.svelte'],
	extends: [...svelte.configs['flat/recommended'], ...svelte.configs['flat/prettier']],
	languageOptions: {
		parserOptions: {
			parser: ts.parser
		}
	}
});

export default ts.config(...tsConfig, ...svelteConfig, {
	ignores: ['.svelte-kit/']
});

tsconfig.eslint.json

{
	"extends": "./tsconfig.json",
	"files": ["eslint.config.js", "svelte.config.js", "vite.config.ts"]
}

tsconfig.json

{
	"extends": "./.svelte-kit/tsconfig.json",
	"compilerOptions": {
		"allowJs": true,
		"checkJs": true,
		"esModuleInterop": true,
		"forceConsistentCasingInFileNames": true,
		"resolveJsonModule": true,
		"skipLibCheck": true,
		"sourceMap": true,
		"strict": true,
		"moduleResolution": "bundler"
	}
}

I am not sure what the extraFileExtensions: [".svelte"], is supposed to do? It seem that I can remove it without any ill effect. Hope this helps.

@robinengler I wanted to answer this Q because it’s important to understand why thigns are done!

The ts parser will ignore files with file extensions it doesn’t expect (such as .svelte). The svelte parser is passed a ts parser instance to handle parsing typescript inside svelte files (sorry if that’s a confusing explanation). To make sure the ts parser will run on this code, we pass the extraFileExtensions parameter to the svelte parser, which in turn passes it to the ts parser to ensure it parses the typescript in svelte files for us. If you don’t, the ts parser will report the following error for every svelte file:

The extension for the file (`.svelte`) is non-standard. You should add `parserOptions.extraFileExtensions` to your config

If you weren’t getting any errors from removing this line, it could be that your config was not actually linting the .svelte files in your project. Hope this helps!

For completeness, here is a full eslint “flat file” configuration that works for Svelte projects that use TypeScript. It also includes Prettier linting.

Maybe an example of such a “flat file” config could be added to the doc of eslint-plugin-svelte, because so far there are only examples of the “old” type of config file (if I’m not mistaken).

// eslint.config.cjs

import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
import eslintPluginSvelte from 'eslint-plugin-svelte';
import js from '@eslint/js';
import svelteParser from 'svelte-eslint-parser';
import tsEslint from 'typescript-eslint';
import tsParser from '@typescript-eslint/parser';

export default [
  js.configs.recommended,
  ...tsEslint.configs.strict,
  ...eslintPluginSvelte.configs['flat/recommended'],
  eslintPluginPrettierRecommended, // must be last to override conflicting rules.
  {
    rules: {
      semi: ['warn', 'always'],
      quotes: [
        'warn',
        'single',
        { avoidEscape: true, allowTemplateLiterals: true },
      ],
      'no-nested-ternary': 'error',
      'linebreak-style': ['error', 'unix'],
      'no-cond-assign': ['error', 'always'],
      'no-console': 'error',
      '@typescript-eslint/sort-type-constituents': 'error',
      'sort-imports': [
        'error',
        {
          ignoreCase: true,
          ignoreDeclarationSort: false,
          ignoreMemberSort: false,
          memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'],
          allowSeparatedGroups: true,
        },
      ],
    },
  },
  {
    files: ['**/*.svelte'],
    languageOptions: {
      parser: svelteParser,
      parserOptions: {
        parser: tsParser,
      },
    },
    rules: {
      'svelte/no-target-blank': 'error',
      'svelte/no-at-debug-tags': 'error',
      'svelte/no-reactive-functions': 'error',
      'svelte/no-reactive-literals': 'error',
    },
  },
];

I agree, having an example would help a lot

I found why my config file was not working with ts files in vscode, yet the command line interface worked as expected!

I needed this config line in vscode: "eslint.experimental.useFlatConfig": true

Also working for me. According to the rollout tracker there is support.

import js from "@eslint/js";
import eslintConfigPrettier from "eslint-config-prettier";
import eslintPluginSvelte from "eslint-plugin-svelte";
import globals from "globals";
import tsEslint from "typescript-eslint";
import vitest from "eslint-plugin-vitest";
import playwright from "eslint-plugin-playwright";

export default [
  js.configs.recommended,
  ...tsEslint.configs.recommended,
  ...eslintPluginSvelte.configs["flat/recommended"],
  eslintConfigPrettier,
  {
    ...playwright.configs["flat/playwright"],
    files: ["tests/**"]
  },
  vitest.configs.recommended,
  ...eslintPluginSvelte.configs["flat/prettier"],
  {
    languageOptions: {
      ecmaVersion: "latest",
      sourceType: "module",
      globals: { ...globals.node, ...globals.browser },
      parserOptions: {
        extraFileExtensions: [".svelte"]
      }
    }
  },
  {
    ignores: [
      ".svelte-kit",
      "build",
      "package",
      "coverage",
      "node_modules",
      "playwright.config.js"
    ]
  }
];