Skip to content

Add svelte/no-reactive-literals rule #203

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

Merged
merged 5 commits into from
Jul 31, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
32 changes: 32 additions & 0 deletions docs/rules/no-reactive-literals.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# (svelte/no-reactive-literals)

> Don't assign literal values in reactive statements

## :book: Rule Details

This rule reports on any assignment of a static, unchanging value within a reactive statement because it's not necessary.

<ESLintCodeBlock>

<!--eslint-skip-->

```svelte
<script>
/* eslint svelte/no-reactive-literals: "error" */
/* ✓ GOOD */
let foo = "bar";

/* ✗ BAD */
$: foo = "bar";
</script>
```
</ESLintCodeBlock>

## :wrench: Options

Nothing

## :mag: Implementation

- [Rule source](https://github.com/ota-meshi/eslint-plugin-svelte/blob/main/src/rules/no-reactive-literals.ts)
- [Test source](https://github.com/ota-meshi/eslint-plugin-svelte/blob/main/tests/src/rules/no-reactive-literals.ts)
69 changes: 69 additions & 0 deletions src/rules/no-reactive-literals.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import type { TSESTree } from "@typescript-eslint/types"
import { createRule } from "../utils"

const labeledStatementBase = `SvelteReactiveStatement > ExpressionStatement > AssignmentExpression`

export default createRule("no-reactive-literals", {
meta: {
docs: {
description: "Don't assign literal values in reactive statements",
category: "Stylistic Issues",
recommended: false,
conflictWithPrettier: false,
},
fixable: "code",
schema: [],
messages: {
noReactiveLiterals: `Do not assign literal values inside reactive statements unless absolutely necessary.`,
},
type: "suggestion",
},
create(context) {
/**
* Reusable method for multiple types of nodes that should warn
*
* @param node TSESTree.AssignmentExpression the node that was found
* @returns void
*/
function warn(node: TSESTree.AssignmentExpression) {
// Move upwards to include the entire reactive statement
const parent = node.parent?.parent

if (!parent) {
return false
}

const source = context.getSourceCode()

return context.report({
node: parent,
loc: parent.loc,
messageId: "noReactiveLiterals",

fix(fixer) {
return [
// Insert "let" + whatever was in there
fixer.insertTextBefore(parent, `let ${source.getText(node)}`),

// Remove the original reactive statement
fixer.remove(parent),
]
},
})
}

return {
// $: foo = "foo";
// $: foo = 1;
[`${labeledStatementBase}[right.type="Literal"]`]: warn,

// $: foo = [];
[`${labeledStatementBase}[right.type="ArrayExpression"][right.elements.length=0]`]:
warn,

// $: foo = {};
[`${labeledStatementBase}[right.type="ObjectExpression"][right.properties.length=0]`]:
warn,
}
},
})
2 changes: 2 additions & 0 deletions src/utils/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import noDynamicSlotName from "../rules/no-dynamic-slot-name"
import noInnerDeclarations from "../rules/no-inner-declarations"
import noNotFunctionHandler from "../rules/no-not-function-handler"
import noObjectInTextMustaches from "../rules/no-object-in-text-mustaches"
import noReactiveLiterals from "../rules/no-reactive-literals"
import noShorthandStylePropertyOverrides from "../rules/no-shorthand-style-property-overrides"
import noSpacesAroundEqualSignsInAttribute from "../rules/no-spaces-around-equal-signs-in-attribute"
import noTargetBlank from "../rules/no-target-blank"
Expand Down Expand Up @@ -47,6 +48,7 @@ export const rules = [
noInnerDeclarations,
noNotFunctionHandler,
noObjectInTextMustaches,
noReactiveLiterals,
noShorthandStylePropertyOverrides,
noSpacesAroundEqualSignsInAttribute,
noTargetBlank,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[
{
"message": "Do not assign literal values inside reactive statements unless absolutely necessary.",
"line": 3,
"column": 5
},
{
"message": "Do not assign literal values inside reactive statements unless absolutely necessary.",
"line": 4,
"column": 5
},
{
"message": "Do not assign literal values inside reactive statements unless absolutely necessary.",
"line": 5,
"column": 5
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<!-- prettier-ignore -->
<script>
$: foo = "foo";
$: bar = [];
$: baz = {};
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<!-- prettier-ignore -->
<script>
let foo = "foo"
let bar = []
let baz = {}
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<!-- prettier-ignore -->
<script>
$: foo = "bar" + "baz"
$: bar = [ "bar" ]
$: baz = { qux : true }
</script>
12 changes: 12 additions & 0 deletions tests/src/rules/no-reactive-literals.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { RuleTester } from "eslint"
import rule from "../../../src/rules/no-reactive-literals"
import { loadTestCases } from "../../utils/utils"

const tester = new RuleTester({
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
},
})

tester.run("no-reactive-literals", rule as any, loadTestCases("no-reactive-literals"))