Skip to content
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

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

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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ 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/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. | |
Expand Down
1 change: 1 addition & 0 deletions docs/rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ 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/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. | |
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/require-each-key': 'error',
'svelte/require-event-dispatcher-types': 'error',
'svelte/require-store-reactive-access': 'error',
Expand Down
5 changes: 5 additions & 0 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<[]>
/**
* require keyed `{#each}` block
* @see https://sveltejs.github.io/eslint-plugin-svelte/rules/require-each-key/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { ReferenceTracker } from '@eslint-community/eslint-utils';
import { getSourceCode } from '../utils/compat.js';
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(
getSourceCode(context).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 requireEachKey from '../rules/require-each-key.js';
import requireEventDispatcherTypes from '../rules/require-event-dispatcher-types.js';
import requireOptimizedStyleAttribute from '../rules/require-optimized-style-attribute.js';
Expand Down Expand Up @@ -135,6 +136,7 @@ export const rules = [
preferConst,
preferDestructuredStoreProps,
preferStyleDirective,
preferSvelteReactivity,
requireEachKey,
requireEventDispatcherTypes,
requireOptimizedStyleAttribute,
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}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script>
import { SvelteURLSearchParams } from "svelte/reactivity";

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

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

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

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

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

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

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 { Set } from "package";

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 { URLSearchParams } from "package";

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 { URL } from "package";

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

{variable}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { RuleTester } from '../../utils/eslint-compat.js';
import rule from '../../../src/rules/prefer-svelte-reactivity.js';
import { loadTestCases } from '../../utils/utils.js';

const tester = new RuleTester({
languageOptions: {
ecmaVersion: 2020,
globals: {
URL: "readonly",
URLSearchParams: "readonly",
},
sourceType: 'module'
}
});

tester.run('prefer-svelte-reactivity', rule as any, loadTestCases('prefer-svelte-reactivity'));
Loading