Home

Awesome

Introduction

eslint-plugin-svelte is the official ESLint plugin for Svelte.
It provides many unique check rules by using the template AST.
You can check on the Online DEMO.

[!NOTE] This document is in development.
Please refer to the document for the version you are using.
For example, https://github.com/sveltejs/eslint-plugin-svelte/blob/eslint-plugin-svelte%402.46.0/README.md and https://github.com/sveltejs/eslint-plugin-svelte/blob/eslint-plugin-svelte%402.46.0/docs

NPM license NPM version NPM downloads NPM downloads NPM downloads NPM downloads NPM downloads Build Status

type-coverage Conventional Commits Code Style: Prettier changesets

:name_badge: What is this plugin?

ESLint plugin for Svelte.
It provides many unique check rules using the AST generated by svelte-eslint-parser.

❗ Attention

Cannot be used with eslint-plugin-svelte3

The svelte-eslint-parser and the eslint-plugin-svelte can not be used with the eslint-plugin-svelte3.

Experimental support for Svelte v5

We are working on support for Svelte v5, but it is still an experimental feature. Please note that rules and features related to Svelte v5 may be changed or removed in minor versions without notice.

<!--DOCS_IGNORE_START-->

Versioning policy

This plugin follows Semantic Versioning.
However, unlike ESLint’s Semantic Versioning Policy, this plugin adds new rules to its configs even in minor releases. For example, if you are using the recommended config, a minor update may add new rules, which could cause new lint errors in your project.
While ESLint’s Semantic Versioning Policy only adds new rules to configs in major releases, most users (myself included) don’t regularly monitor new rules. This makes it challenging to manually add them to projects whenever they are introduced.
By adding new rules to configs in minor releases, this plugin ensures users can adopt them more easily. If any new rules cause issues, you can simply disable them. I believe this approach helps maintain and improve code quality with minimal effort.

Migration Guide

To migrate from eslint-plugin-svelte v1, or @ota-meshi/eslint-plugin-svelte, please refer to the migration guide.

:book: Documentation

See documents.

:cd: Installation

npm install --save-dev eslint eslint-plugin-svelte svelte

Requirements

<!--DOCS_IGNORE_END-->

:book: Usage

<!--USAGE_SECTION_START--> <!--USAGE_GUIDE_START-->

Configuration

Use eslint.config.js file to configure rules. See also: https://eslint.org/docs/latest/use/configure/configuration-files-new.

Example eslint.config.js:

import eslintPluginSvelte from 'eslint-plugin-svelte';
export default [
  // add more generic rule sets here, such as:
  // js.configs.recommended,
  ...eslintPluginSvelte.configs.recommended,
  {
    rules: {
      // override/add rules settings here, such as:
      // 'svelte/rule-name': 'error'
    }
  }
];

This plugin provides configs:

See the rule list to get the rules that this plugin provides.

Parser Configuration

If you have specified a parser, you need to configure a parser for .svelte.

For example, if you are using the "@typescript-eslint/parser", and if you want to use TypeScript in <script> of .svelte, you need to add more parserOptions configuration.

import eslintPluginSvelte from 'eslint-plugin-svelte';
import * as svelteParser from 'svelte-eslint-parser';
import * as typescriptParser from '@typescript-eslint/parser';
export default [
  ...js.configs.recommended,
  ...eslintPluginSvelte.configs.recommended,
  {
    files: ['**/*.svelte'],
    languageOptions: {
      parser: svelteParser,
      parserOptions: {
        parser: typescriptParser,
        project: './path/to/your/tsconfig.json',
        extraFileExtensions: ['.svelte']
      }
    }
  }
];

If you have a mix of TypeScript and JavaScript in your project, use a multiple parser configuration.

import eslintPluginSvelte from 'eslint-plugin-svelte';
import * as svelteParser from 'svelte-eslint-parser';
import * as typescriptParser from '@typescript-eslint/parser';
import espree from 'espree';
export default [
  ...js.configs.recommended,
  ...eslintPluginSvelte.configs.recommended,
  {
    files: ['**/*.svelte'],
    languageOptions: {
      parser: svelteParser,
      parserOptions: {
        parser: {
          // Specify a parser for each lang.
          ts: typescriptParser,
          js: espree,
          typescript: typescriptParser
        },
        project: './path/to/your/tsconfig.json',
        extraFileExtensions: ['.svelte']
      }
    }
  }
];

See also https://github.com/sveltejs/svelte-eslint-parser#readme.

::: warning ❗ Attention

The TypeScript parser uses a singleton internally and it will only use the options given to it when it was first initialized. If trying to change the options for a different file or override, the parser will simply ignore the new options (which may result in an error). See typescript-eslint/typescript-eslint#6778 for some context.

:::

Specify svelte.config.js

If you are using eslint.config.js, we recommend that you import and specify svelte.config.js. By specifying it, some rules of eslint-plugin-svelte will read it and try to behave well for you by default. Some Svelte configurations will be statically loaded from svelte.config.js even if you don't specify it, but you need to specify it to make it work better.

Example eslint.config.js:

import eslintPluginSvelte from 'eslint-plugin-svelte';
import svelteConfig from './svelte.config.js';
export default [
  ...eslintPluginSvelte.configs.recommended,
  {
    files: [
      '**/*.svelte',
      '*.svelte'
      // Add more files if you need.
      // '**/*.svelte.ts', '*.svelte.ts', '**/*.svelte.js', '*.svelte.js',
    ],
    languageOptions: {
      parserOptions: {
        // Specify the `svelte.config.js`.
        svelteConfig
      }
    }
  }
];

settings.svelte

You can change the behavior of this plugin with some settings.

e.g.

export default [
  // ...
  {
    settings: {
      svelte: {
        ignoreWarnings: [
          '@typescript-eslint/no-unsafe-assignment',
          '@typescript-eslint/no-unsafe-member-access'
        ],
        compileOptions: {
          postcss: {
            configFilePath: './path/to/my/postcss.config.js'
          }
        },
        kit: {
          files: {
            routes: 'src/routes'
          }
        }
      }
    }
  }
  // ...
];

settings.svelte.ignoreWarnings

Specifies an array of rules that ignore reports in the template.
For example, set rules on the template that cannot avoid false positives.

settings.svelte.compileOptions

Specifies options for Svelte compile. Effects rules that use Svelte compile. The target rules are svelte/valid-compile and svelte/no-unused-svelte-ignore. Note that it has no effect on ESLint's custom parser.

settings.svelte.kit

::: warning

Even if you don't specify settings.svelte.kit, the rules will try to load information from svelte.config.js, so specify settings.svelte.kit if the default doesn't work.

:::

If you use SvelteKit with not default configuration, you need to set below configurations. The schema is subset of SvelteKit's configuration. Therefore please check SvelteKit docs for more details.

e.g.

export default [
  // ...
  {
    settings: {
      svelte: {
        kit: {
          files: {
            routes: 'src/routes'
          }
        }
      }
    }
  }
  // ...
];

:computer: Editor Integrations

Visual Studio Code

Use the dbaeumer.vscode-eslint extension that Microsoft provides officially.

You have to configure the eslint.validate option of the extension to check .svelte files, because the extension targets only *.js or *.jsx files by default.

Example .vscode/settings.json:

{
  "eslint.validate": ["javascript", "javascriptreact", "svelte"]
}
<!--USAGE_GUIDE_END--> <!--USAGE_SECTION_END-->

:white_check_mark: Rules

<!-- prettier-ignore-start --> <!--RULES_SECTION_START-->

:wrench: Indicates that the rule is fixable, and using --fix option on the command line can automatically fix some of the reported problems.
:bulb: Indicates that some problems reported by the rule are manually fixable by editor suggestions.
:star: Indicates that the rule is included in the plugin:svelte/recommended config.

<!--RULES_TABLE_START-->

Possible Errors

These rules relate to possible syntax or logic errors in Svelte code:

Rule IDDescription
svelte/infinite-reactive-loopSvelte runtime prevents calling the same reactive statement twice in a microtask. But between different microtask, it doesn't prevent.
svelte/no-deprecated-raw-special-elementsRecommends not using raw special elements in Svelte versions previous to 5.:wrench:
svelte/no-dom-manipulatingdisallow DOM manipulating
svelte/no-dupe-else-if-blocksdisallow duplicate conditions in {#if} / {:else if} chains:star:
svelte/no-dupe-on-directivesdisallow duplicate on: directives
svelte/no-dupe-style-propertiesdisallow duplicate style properties:star:
svelte/no-dupe-use-directivesdisallow duplicate use: directives
svelte/no-dynamic-slot-namedisallow dynamic slot name:star::wrench:
svelte/no-export-load-in-svelte-module-in-kit-pagesdisallow exporting load functions in *.svelte module in SvelteKit page components.
svelte/no-not-function-handlerdisallow use of not function in event handler:star:
svelte/no-object-in-text-mustachesdisallow objects in text mustache interpolation:star:
svelte/no-reactive-reassigndisallow reassigning reactive values
svelte/no-shorthand-style-property-overridesdisallow shorthand style properties that override related longhand properties:star:
svelte/no-store-asyncdisallow using async/await inside svelte stores because it causes issues with the auto-unsubscribing features
svelte/no-unknown-style-directive-propertydisallow unknown style:property:star:
svelte/require-store-callbacks-use-set-paramstore callbacks must use set param
svelte/require-store-reactive-accessdisallow to use of the store itself as an operand. Need to use $ prefix or get function.:wrench:
svelte/valid-compiledisallow warnings when compiling.:star:
svelte/valid-prop-names-in-kit-pagesdisallow props other than data or errors in SvelteKit page components.

Security Vulnerability

These rules relate to security vulnerabilities in Svelte code:

Rule IDDescription
svelte/no-at-html-tagsdisallow use of {@html} to prevent XSS attack:star:
svelte/no-target-blankdisallow target="_blank" attribute without rel="noopener noreferrer"

Best Practices

These rules relate to better ways of doing things to help you avoid problems:

Rule IDDescription
svelte/block-langdisallows the use of languages other than those specified in the configuration for the lang attribute of <script> and <style> blocks.
svelte/button-has-typedisallow usage of button without an explicit type attribute
svelte/no-at-debug-tagsdisallow the use of {@debug}:star:
svelte/no-ignored-unsubscribedisallow ignoring the unsubscribe method returned by the subscribe() on Svelte stores.
svelte/no-immutable-reactive-statementsdisallow reactive statements that don't reference reactive values.
svelte/no-inline-stylesdisallow attributes and directives that produce inline styles
svelte/no-inspectWarns against the use of $inspect directive
svelte/no-reactive-functionsit's not necessary to define functions in reactive statements:bulb:
svelte/no-reactive-literalsdon't assign literal values in reactive statements:bulb:
svelte/no-svelte-internalsvelte/internal will be removed in Svelte 6.
svelte/no-unused-class-namedisallow the use of a class in the template without a corresponding style
svelte/no-unused-svelte-ignoredisallow unused svelte-ignore comments:star:
svelte/no-useless-mustachesdisallow unnecessary mustache interpolations:wrench:
svelte/prefer-destructured-store-propsdestructure values from object stores for better change tracking & fewer redraws:bulb:
svelte/require-each-keyrequire keyed {#each} block
svelte/require-event-dispatcher-typesrequire type parameters for createEventDispatcher
svelte/require-optimized-style-attributerequire style attributes that can be optimized
svelte/require-stores-initrequire initial value in store
svelte/valid-each-keyenforce keys to use variables defined in the {#each} block

Stylistic Issues

These rules relate to style guidelines, and are therefore quite subjective:

Rule IDDescription
svelte/derived-has-same-inputs-outputsderived store should use same variable names between values and callback
svelte/first-attribute-linebreakenforce the location of first attribute:wrench:
svelte/html-closing-bracket-new-lineRequire or disallow a line break before tag's closing brackets:wrench:
svelte/html-closing-bracket-spacingrequire or disallow a space before tag's closing brackets:wrench:
svelte/html-quotesenforce quotes style of HTML attributes:wrench:
svelte/html-self-closingenforce self-closing style:wrench:
svelte/indentenforce consistent indentation:wrench:
svelte/max-attributes-per-lineenforce the maximum number of attributes per line:wrench:
svelte/mustache-spacingenforce unified spacing in mustache:wrench:
svelte/no-extra-reactive-curliesdisallow wrapping single reactive statements in curly braces:bulb:
svelte/no-restricted-html-elementsdisallow specific HTML elements
svelte/no-spaces-around-equal-signs-in-attributedisallow spaces around equal signs in attribute:wrench:
svelte/prefer-class-directiverequire class directives instead of ternary expressions:wrench:
svelte/prefer-style-directiverequire style directives instead of style attribute:wrench:
svelte/shorthand-attributeenforce use of shorthand syntax in attribute:wrench:
svelte/shorthand-directiveenforce use of shorthand syntax in directives:wrench:
svelte/sort-attributesenforce order of attributes:wrench:
svelte/spaced-html-commentenforce consistent spacing after the <!-- and before the --> in a HTML comment:wrench:

Extension Rules

These rules extend the rules provided by ESLint itself, or other plugins to work well in Svelte:

Rule IDDescription
svelte/no-inner-declarationsdisallow variable or function declarations in nested blocks:star:
svelte/no-trailing-spacesdisallow trailing whitespace at the end of lines:wrench:

SvelteKit

These rules relate to SvelteKit and its best Practices.

Rule IDDescription
svelte/no-goto-without-basedisallow using goto() without the base path

Experimental

:warning: These rules are considered experimental and may change or be removed in the future:

Rule IDDescription
svelte/experimental-require-slot-typesrequire slot type declaration using the $$Slots interface
svelte/experimental-require-strict-eventsrequire the strictEvents attribute on <script> tags

System

These rules relate to this plugin works:

Rule IDDescription
svelte/comment-directivesupport comment-directives in HTML template:star:
svelte/systemsystem rule for working this plugin:star:

Deprecated

Rule IDReplaced by
svelte/@typescript-eslint/no-unnecessary-conditionThis rule is no longer needed when using svelte-eslint-parser>=v0.19.0.
<!--RULES_TABLE_END--> <!--RULES_SECTION_END--> <!-- prettier-ignore-end --> <!--DOCS_IGNORE_START-->

:beers: Contributing

Welcome contributing!

Please use GitHub's Issues/PRs.

See also CONTRIBUTING.md

Working With Rules

This plugin uses svelte-eslint-parser for the parser. Check here to find out about AST.

<!--DOCS_IGNORE_END-->

:lock: License

See the LICENSE file for license rights and limitations (MIT).