Skip to content

feat: added the prefer-svelte-reactivity rule #1151

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/rich-colts-nail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'eslint-plugin-svelte': minor
---

feat: added the `prefer-svelte-reactivity` rule
17 changes: 9 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@

## Introduction

`eslint-plugin-svelte` is the official [ESLint](https://eslint.org/) plugin for [Svelte](https://svelte.dev/).
It leverages the AST generated by [svelte-eslint-parser](https://github.com/sveltejs/svelte-eslint-parser) to provide custom linting for Svelte.
`eslint-plugin-svelte` is the official [ESLint](https://eslint.org/) plugin for [Svelte](https://svelte.dev/).
It leverages the AST generated by [svelte-eslint-parser](https://github.com/sveltejs/svelte-eslint-parser) to provide custom linting for Svelte.
Note that `eslint-plugin-svelte` and `svelte-eslint-parser` cannot be used alongside [eslint-plugin-svelte3](https://github.com/sveltejs/eslint-plugin-svelte3).

<!--USAGE_SECTION_START-->
Expand Down Expand Up @@ -219,8 +219,8 @@ export default [

## Editor Integrations

**Visual Studio Code**
Install [dbaeumer.vscode-eslint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint).
**Visual Studio Code**
Install [dbaeumer.vscode-eslint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint).
Configure `.svelte` files in `.vscode/settings.json`:

```json
Expand All @@ -247,8 +247,8 @@ This project follows [Semantic Versioning](https://semver.org/). Unlike [ESLint
<!-- prettier-ignore-start -->
<!--RULES_SECTION_START-->

:wrench: Indicates that the rule is fixable, and using `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fixing-problems) can automatically fix some of the reported problems.
:bulb: Indicates that some problems reported by the rule are manually fixable by editor [suggestions](https://eslint.org/docs/developer-guide/working-with-rules#providing-suggestions).
:wrench: Indicates that the rule is fixable, and using `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fixing-problems) can automatically fix some of the reported problems.
:bulb: Indicates that some problems reported by the rule are manually fixable by editor [suggestions](https://eslint.org/docs/developer-guide/working-with-rules#providing-suggestions).
:star: Indicates that the rule is included in the `plugin:svelte/recommended` config.

<!--RULES_TABLE_START-->
Expand All @@ -272,7 +272,8 @@ These rules relate to possible syntax or logic errors in Svelte code:
| [svelte/no-shorthand-style-property-overrides](https://sveltejs.github.io/eslint-plugin-svelte/rules/no-shorthand-style-property-overrides/) | disallow shorthand style properties that override related longhand properties | :star: |
| [svelte/no-store-async](https://sveltejs.github.io/eslint-plugin-svelte/rules/no-store-async/) | disallow using async/await inside svelte stores because it causes issues with the auto-unsubscribing features | :star: |
| [svelte/no-unknown-style-directive-property](https://sveltejs.github.io/eslint-plugin-svelte/rules/no-unknown-style-directive-property/) | disallow unknown `style:property` | :star: |
| [svelte/require-store-callbacks-use-set-param](https://sveltejs.github.io/eslint-plugin-svelte/rules/require-store-callbacks-use-set-param/) | store callbacks must use `set` param | :bulb: |
| [svelte/prefer-svelte-reactivity](https://sveltejs.github.io/eslint-plugin-svelte/rules/prefer-svelte-reactivity/) | disallow using built-in classes where a reactive alternative is provided by svelte/reactivity | :star: |
| [svelte/require-store-callbacks-use-set-param](https://sveltejs.github.io/eslint-plugin-svelte/rules/require-store-callbacks-use-set-param/) | store callbacks must use `set` param | |
| [svelte/require-store-reactive-access](https://sveltejs.github.io/eslint-plugin-svelte/rules/require-store-reactive-access/) | disallow to use of the store itself as an operand. Need to use $ prefix or get function. | :star::wrench: |
| [svelte/valid-compile](https://sveltejs.github.io/eslint-plugin-svelte/rules/valid-compile/) | disallow warnings when compiling. | |
| [svelte/valid-style-parse](https://sveltejs.github.io/eslint-plugin-svelte/rules/valid-style-parse/) | require valid style element parsing | |
Expand Down Expand Up @@ -400,7 +401,7 @@ These rules relate to this plugin works:

## Contributing

Contributions are welcome! Please open an issue or submit a PR. For more details, see [CONTRIBUTING.md](./CONTRIBUTING.md).
Contributions are welcome! Please open an issue or submit a PR. For more details, see [CONTRIBUTING.md](./CONTRIBUTING.md).
Refer to [svelte-eslint-parser](https://github.com/sveltejs/svelte-eslint-parser) for AST details.

<!--DOCS_IGNORE_END-->
Expand Down
7 changes: 4 additions & 3 deletions docs/rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ sidebarDepth: 0

# Available Rules

:wrench: Indicates that the rule is fixable, and using `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fixing-problems) can automatically fix some of the reported problems.
:bulb: Indicates that some problems reported by the rule are manually fixable by editor [suggestions](https://eslint.org/docs/developer-guide/working-with-rules#providing-suggestions).
:wrench: Indicates that the rule is fixable, and using `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fixing-problems) can automatically fix some of the reported problems.
:bulb: Indicates that some problems reported by the rule are manually fixable by editor [suggestions](https://eslint.org/docs/developer-guide/working-with-rules#providing-suggestions).
:star: Indicates that the rule is included in the `plugin:svelte/recommended` config.

<!-- This file is automatically generated in tools/update-docs-rules-index.js, do not change! -->
Expand All @@ -29,7 +29,8 @@ These rules relate to possible syntax or logic errors in Svelte code:
| [svelte/no-shorthand-style-property-overrides](./rules/no-shorthand-style-property-overrides.md) | disallow shorthand style properties that override related longhand properties | :star: |
| [svelte/no-store-async](./rules/no-store-async.md) | disallow using async/await inside svelte stores because it causes issues with the auto-unsubscribing features | :star: |
| [svelte/no-unknown-style-directive-property](./rules/no-unknown-style-directive-property.md) | disallow unknown `style:property` | :star: |
| [svelte/require-store-callbacks-use-set-param](./rules/require-store-callbacks-use-set-param.md) | store callbacks must use `set` param | :bulb: |
| [svelte/prefer-svelte-reactivity](./rules/prefer-svelte-reactivity.md) | disallow using built-in classes where a reactive alternative is provided by svelte/reactivity | :star: |
| [svelte/require-store-callbacks-use-set-param](./rules/require-store-callbacks-use-set-param.md) | store callbacks must use `set` param | |
| [svelte/require-store-reactive-access](./rules/require-store-reactive-access.md) | disallow to use of the store itself as an operand. Need to use $ prefix or get function. | :star::wrench: |
| [svelte/valid-compile](./rules/valid-compile.md) | disallow warnings when compiling. | |
| [svelte/valid-style-parse](./rules/valid-style-parse.md) | require valid style element parsing | |
Expand Down
68 changes: 68 additions & 0 deletions docs/rules/prefer-svelte-reactivity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
---
pageClass: 'rule-details'
sidebarDepth: 0
title: 'svelte/prefer-svelte-reactivity'
description: 'disallow using built-in classes where a reactive alternative is provided by svelte/reactivity'
---

# svelte/prefer-svelte-reactivity

> disallow using built-in classes where a reactive alternative is provided by svelte/reactivity

- :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> **_This rule has not been released yet._** </badge>
- :gear: This rule is included in `"plugin:svelte/recommended"`.

## :book: Rule Details

The built-in `Date`, `Map`, `Set`, `URL` and `URLSearchParams` classes are often used in frontend code, however, their properties and methods are not reactive. Because of that, Svelte provides reactive versions of these 5 builtins as part of the "svelte/reactivity" package. This rule reports usage of the built-in versions in Svelte code.

<!--eslint-skip-->

```svelte
<script>
/* eslint svelte/prefer-svelte-reactivity: "error" */

import {
SvelteDate,
SvelteMap,
SvelteSet,
SvelteURL,
SvelteURLSearchParams
} from 'svelte/reactivity';

/* ✓ GOOD */

const a = new SvelteDate(8.64e15);
const b = new SvelteMap([
[1, 'one'],
[2, 'two']
]);
const c = new SvelteSet([1, 2, 1, 3, 3]);
const d = new SvelteURL('https://svelte.dev/');
const e = new SvelteURLSearchParams('foo=1&bar=2');

/* ✗ BAD */

const f = new Date(8.64e15);
const g = new Map([
[1, 'one'],
[2, 'two']
]);
const h = new Set([1, 2, 1, 3, 3]);
const i = new URL('https://svelte.dev/');
const j = new URLSearchParams('foo=1&bar=2');
</script>
```

## :wrench: Options

Nothing.

## :books: Further Reading

- [svelte/reactivity documentation](https://svelte.dev/docs/svelte/svelte-reactivity)

## :mag: Implementation

- [Rule source](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/packages/eslint-plugin-svelte/src/rules/prefer-svelte-reactivity.ts)
- [Test source](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/packages/eslint-plugin-svelte/tests/src/rules/prefer-svelte-reactivity.ts)
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const config: Linter.Config[] = [
'svelte/no-unused-svelte-ignore': 'error',
'svelte/no-useless-children-snippet': 'error',
'svelte/no-useless-mustaches': 'error',
'svelte/prefer-svelte-reactivity': 'error',
'svelte/prefer-writable-derived': 'error',
'svelte/require-each-key': 'error',
'svelte/require-event-dispatcher-types': 'error',
Expand Down
19 changes: 12 additions & 7 deletions packages/eslint-plugin-svelte/src/rule-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,11 @@ export interface RuleOptions {
* @see https://sveltejs.github.io/eslint-plugin-svelte/rules/prefer-style-directive/
*/
'svelte/prefer-style-directive'?: Linter.RuleEntry<[]>
/**
* disallow using built-in classes where a reactive alternative is provided by svelte/reactivity
* @see https://sveltejs.github.io/eslint-plugin-svelte/rules/prefer-svelte-reactivity/
*/
'svelte/prefer-svelte-reactivity'?: Linter.RuleEntry<[]>
/**
* Prefer using writable $derived instead of $state and $effect
* @see https://sveltejs.github.io/eslint-plugin-svelte/rules/prefer-writable-derived/
Expand Down Expand Up @@ -396,9 +401,9 @@ export interface RuleOptions {
/* ======= Declarations ======= */
// ----- svelte/@typescript-eslint/no-unnecessary-condition -----
type SvelteTypescriptEslintNoUnnecessaryCondition = []|[{

allowConstantLoopConditions?: boolean

allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean
}]
// ----- svelte/block-lang -----
Expand All @@ -421,7 +426,7 @@ type SvelteCommentDirective = []|[{
// ----- svelte/consistent-selector-style -----
type SvelteConsistentSelectorStyle = []|[{
checkGlobal?: boolean

style?: []|[("class" | "id" | "type")]|[("class" | "id" | "type"), ("class" | "id" | "type")]|[("class" | "id" | "type"), ("class" | "id" | "type"), ("class" | "id" | "type")]
}]
// ----- svelte/first-attribute-linebreak -----
Expand Down Expand Up @@ -509,11 +514,11 @@ type SvelteNoReactiveReassign = []|[{
}]
// ----- svelte/no-restricted-html-elements -----
type SvelteNoRestrictedHtmlElements = [(string | {

elements?: [string, ...(string)[]]
message?: string
}), ...((string | {

elements?: [string, ...(string)[]]
message?: string
}))[]]
Expand All @@ -529,7 +534,7 @@ type SvelteNoTrailingSpaces = []|[{
}]
// ----- svelte/no-unknown-style-directive-property -----
type SvelteNoUnknownStyleDirectiveProperty = []|[{

ignoreProperties?: [string, ...(string)[]]
ignorePrefixed?: boolean
}]
Expand Down Expand Up @@ -589,4 +594,4 @@ type SvelteSpacedHtmlComment = []|[("always" | "never")]
// ----- svelte/valid-compile -----
type SvelteValidCompile = []|[{
ignoreWarnings?: boolean
}]
}]
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { ReferenceTracker } from '@eslint-community/eslint-utils';
import { createRule } from '../utils/index.js';

export default createRule('prefer-svelte-reactivity', {
meta: {
docs: {
description:
'disallow using built-in classes where a reactive alternative is provided by svelte/reactivity',
category: 'Possible Errors',
recommended: true
},
schema: [],
messages: {
dateUsed: 'Found a usage of the built-in Date class. Use a SvelteDate instead.',
mapUsed: 'Found a usage of the built-in Map class. Use a SvelteMap instead.',
setUsed: 'Found a usage of the built-in Set class. Use a SvelteSet instead.',
urlUsed: 'Found a usage of the built-in URL class. Use a SvelteURL instead.',
urlSearchParamsUsed:
'Found a usage of the built-in URLSearchParams class. Use a SvelteURLSearchParams instead.'
},
type: 'problem', // 'problem', or 'layout',
conditions: [
{
svelteVersions: ['5'],
svelteFileTypes: ['.svelte', '.svelte.[js|ts]']
}
]
},
create(context) {
return {
Program() {
const referenceTracker = new ReferenceTracker(context.sourceCode.scopeManager.globalScope!);
for (const { node, path } of referenceTracker.iterateGlobalReferences({
Date: {
[ReferenceTracker.CONSTRUCT]: true
},
Map: {
[ReferenceTracker.CONSTRUCT]: true
},
Set: {
[ReferenceTracker.CONSTRUCT]: true
},
URL: {
[ReferenceTracker.CALL]: true,
[ReferenceTracker.CONSTRUCT]: true,
[ReferenceTracker.READ]: true
},
URLSearchParams: {
[ReferenceTracker.CALL]: true,
[ReferenceTracker.CONSTRUCT]: true,
[ReferenceTracker.READ]: true
}
})) {
const typeToMessageId: Record<string, string> = {
Date: 'dateUsed',
Map: 'mapUsed',
Set: 'setUsed',
URL: 'urlUsed',
URLSearchParams: 'urlSearchParamsUsed'
};
context.report({
messageId: typeToMessageId[path[0]],
node
});
}
}
};
}
});
2 changes: 2 additions & 0 deletions packages/eslint-plugin-svelte/src/utils/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import preferClassDirective from '../rules/prefer-class-directive.js';
import preferConst from '../rules/prefer-const.js';
import preferDestructuredStoreProps from '../rules/prefer-destructured-store-props.js';
import preferStyleDirective from '../rules/prefer-style-directive.js';
import preferSvelteReactivity from '../rules/prefer-svelte-reactivity.js';
import preferWritableDerived from '../rules/prefer-writable-derived.js';
import requireEachKey from '../rules/require-each-key.js';
import requireEventDispatcherTypes from '../rules/require-event-dispatcher-types.js';
Expand Down Expand Up @@ -137,6 +138,7 @@ export const rules = [
preferConst,
preferDestructuredStoreProps,
preferStyleDirective,
preferSvelteReactivity,
preferWritableDerived,
requireEachKey,
requireEventDispatcherTypes,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script>
const variable = new Date(8.64e15);
</script>

{variable}
Comment on lines +1 to +5
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don’t think this needs to be reported. If there’s no reassignment, it shouldn’t need to be reactive.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not about reassignment, it's about internal changes. I'd prefer to be this overly-broad. The alternative is tracking calls to every method that modifies the object (I count 16 on Date alone) or writing to any property.

On top of that, once something is exported, it should be reported as well (mostly relevant for .svelte.ts files)

I am not sure it's worth it, what do you think?

Copy link
Member

@baseballyama baseballyama Mar 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What I’m saying is the same thing.

// It should be SvelteMap because there is internal changes.
const foo = new Map();
foo.set("a", 0);

// It should not be reported because there is no internal changes.
const bar = new Map();

On top of that, once something is exported, it should be reported as well (mostly relevant for .svelte.ts files)

If we think of svelte.js as “reactive files,” it should be fine to report aggressively.

Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script>
const variable = new Map([[1, "one"], [2, "two"]]);
</script>

{variable}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script>
const variable = new Set([1, 2, 1, 3, 3]);
</script>

{variable}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script>
const variable = new URLSearchParams("foo=1&bar=2");
</script>

{variable}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script>
const variable = new URL("https://svelte.dev/");
</script>

{variable}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script>
import { SvelteDate as Date } from "svelte/reactivity";

const variable = new Date(8.64e15);
</script>

{variable}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script>
import { SvelteMap as Map } from "svelte/reactivity";

const variable = new Map([[1, "one"], [2, "two"]]);
</script>

{variable}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script>
import { SvelteSet as Set } from "svelte/reactivity";

const variable = new Set([1, 2, 1, 3, 3]);
</script>

{variable}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script>
import { SvelteURLSearchParams as URLSearchParams } from "svelte/reactivity";

const variable = new URLSearchParams("foo=1&bar=2");
</script>

{variable}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script>
import { SvelteURL as URL } from "svelte/reactivity";

const variable = new URL("https://svelte.dev/");
</script>

{variable}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script>
import { SvelteDate } from "svelte/reactivity";

const variable = new SvelteDate(8.64e15);
</script>

{variable}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script>
import { SvelteMap } from "svelte/reactivity";

const variable = new SvelteMap([[1, "one"], [2, "two"]]);
</script>

{variable}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script>
import { SvelteSet } from "svelte/reactivity";

const variable = new SvelteSet([1, 2, 1, 3, 3]);
</script>

{variable}
Loading
Loading