eslint-plugin-svelte
Version:
ESLint plugin for Svelte using AST
59 lines (58 loc) • 2.25 kB
JavaScript
import { createRule } from '../utils/index.js';
export default createRule('no-reactive-functions', {
meta: {
docs: {
description: "it's not necessary to define functions in reactive statements",
category: 'Best Practices',
recommended: true
},
hasSuggestions: true,
schema: [],
messages: {
noReactiveFns: `Do not create functions inside reactive statements unless absolutely necessary.`,
fixReactiveFns: `Move the function out of the reactive statement`
},
type: 'suggestion',
conditions: [
{
svelteVersions: ['3/4']
},
{
svelteVersions: ['5'],
runes: [false, 'undetermined']
}
]
},
create(context) {
return {
// $: foo = () => { ... }
[`SvelteReactiveStatement > ExpressionStatement > AssignmentExpression > :function`](node) {
// Move upwards to include the entire label
const parent = node.parent?.parent?.parent;
if (!parent) {
return false;
}
const source = context.sourceCode;
return context.report({
node: parent,
loc: parent.loc,
messageId: 'noReactiveFns',
suggest: [
{
messageId: 'fixReactiveFns',
fix(fixer) {
const tokens = source.getFirstTokens(parent, {
includeComments: false,
count: 3
});
const noExtraSpace = source.isSpaceBetweenTokens(tokens[1], tokens[2]);
// Replace the entire reactive label with "const"
return fixer.replaceTextRange([tokens[0].range[0], tokens[1].range[1]], noExtraSpace ? 'const' : 'const ');
}
}
]
});
}
};
}
});