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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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 @@ -273,6 +273,7 @@ These rules relate to possible syntax or logic errors in Svelte code:
| [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-top-level-browser-globals](https://sveltejs.github.io/eslint-plugin-svelte/rules/no-top-level-browser-globals/) | disallow using top-level browser global variables | |
| [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 | :bulb: |
| [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 @@ -30,6 +30,7 @@ These rules relate to possible syntax or logic errors in Svelte code:
| [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-top-level-browser-globals](./rules/no-top-level-browser-globals.md) | disallow using top-level browser global variables | |
| [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 | :bulb: |
| [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/prefer-writable-derived': 'error',
'svelte/require-each-key': 'error',
'svelte/require-event-dispatcher-types': '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 @@ -316,6 +316,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
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
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.CONSTRUCT]: true
},
URLSearchParams: {
[ReferenceTracker.CONSTRUCT]: 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 @@ -62,6 +62,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 @@ -141,6 +142,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,3 @@
{
"svelte": ">=5.0.0"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<script>
const variable = new Date(8.64e15);

variable.setDate(24);
variable.setFullYear(1968);
variable.setFullYear(1968, 10);
variable.setFullYear(1968, 10, 3);
variable.setHours(23);
variable.setHours(23, 59);
variable.setHours(23, 59, 59);
variable.setHours(23, 59, 59, 999);
variable.setMilliseconds(999);
variable.setMinutes(59);
variable.setMinutes(59, 59);
variable.setMinutes(59, 59, 999);
variable.setMonth(11);
variable.setMonth(11, 23);
variable.setSeconds(59);
variable.setSeconds(59, 999);
variable.setTime(123456);
variable.setUTCDate(23);
variable.setUTCFullYear(1968);
variable.setUTCFullYear(1968, 10);
variable.setUTCFullYear(1968, 10, 3);
variable.setUTCHours(23);
variable.setUTCHours(23, 59);
variable.setUTCHours(23, 59, 59);
variable.setUTCHours(23, 59, 59, 999);
variable.setUTCMilliseconds(420);
variable.setUTCMinutes(59);
variable.setUTCMinutes(59, 59);
variable.setUTCMinutes(59, 59, 999);
variable.setUTCMonth(10);
variable.setUTCMonth(10, 3);
variable.setUTCSeconds(59);
variable.setUTCSeconds(59, 999);
variable.setYear(1968);
</script>

{variable}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const variable1 = new Date(8.64e15);
const variable2 = new Map([[1, "one"], [2, "two"]]);
const variable3 = new Set([1, 2, 1, 3, 3]);
const variable4 = new URLSearchParams("foo=1&bar=2");
const variable5 = new URL("https://svelte.dev/");

export variable1;
export variable2;
export variable3;
export variable4;
export variable5;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script>
const variable = new Map([[1, "one"], [2, "two"]]);

variable.clear();
variable.delete(1);
variable.set(1, "two");
</script>

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

variable.add(42);
variable.clear();
variable.delete(42);
</script>

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

variable.append("baz", "3");
variable.delete("foo");
variable.delete("bar", "42");
variable.set("foo", "-1")
variable.sort();
</script>

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

variable.hash = "anchor";
variable.host = "example.test";
variable.hostname = "example.test";
variable.href = "https://svelte.dev/";
variable.password = "passwd";
variable.pathname = "tutorial";
variable.port = "80";
variable.protocol = "https";
variable.search = "foo=bar";
variable.username = "usr";
</script>

{variable}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"svelte": ">=5.0.0"
}
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,40 @@
<script>
const variable = new Date(8.64e15);

console.log(Date.now());
console.log(Date.parse("1970-01-01T00:00:00Z"));
console.log(Date.UTC(96, 1, 2, 3, 4, 5));
console.log(variable.getDate());
console.log(variable.getDay());
console.log(variable.getFullYear());
console.log(variable.getHours());
console.log(variable.getMilliseconds());
console.log(variable.getMinutes());
console.log(variable.getMonth());
console.log(variable.getSeconds());
console.log(variable.getTime());
console.log(variable.getTimezoneOffset());
console.log(variable.getUTCDate());
console.log(variable.getUTCDay());
console.log(variable.getUTCFullYear());
console.log(variable.getUTCHours());
console.log(variable.getUTCMilliseconds());
console.log(variable.getUTCMinutes());
console.log(variable.getUTCMonth());
console.log(variable.getUTCSeconds());
console.log(variable.getYear());
console.log(variable.toDateString());
console.log(variable.toISOString());
console.log(variable.toJSON());
console.log(variable.toLocaleDateString());
console.log(variable.toLocaleString());
console.log(variable.toLocaleTimeString());
console.log(variable.toString());
console.log(variable.toTemporalInstant());
console.log(variable.toTimeString());
console.log(variable.toUTCString());
console.log(variable.valueOf());
console.log(variable[Symbol.toPrimitive]("string"));
</script>

{variable}
Loading
Loading