|
| 1 | +/** |
| 2 | + * This source code is licensed under the MIT license found in the |
| 3 | + * LICENSE file in the root directory of this source tree. |
| 4 | + */ |
| 5 | + |
| 6 | +'use strict'; |
| 7 | + |
| 8 | +const HOOKS = ['useCallback', 'useEffect', 'useLayoutEffect', 'useMemo']; |
| 9 | + |
| 10 | +function isDependencyArrayHook(node) { |
| 11 | + if (node.type === 'Identifier') { |
| 12 | + return HOOKS.includes(node.name); |
| 13 | + } |
| 14 | + return false; |
| 15 | +} |
| 16 | + |
| 17 | +//------------------------------------------------------------------------------ |
| 18 | +// Rule Definition |
| 19 | +//------------------------------------------------------------------------------ |
| 20 | + |
| 21 | +/** @type {import('eslint').Rule.RuleModule} */ |
| 22 | +module.exports = { |
| 23 | + meta: { |
| 24 | + type: 'suggestion', |
| 25 | + fixable: 'code', |
| 26 | + docs: { |
| 27 | + category: 'Stylistic Issues', |
| 28 | + description: 'require react dependency arrays to be sorted', |
| 29 | + recommended: false, |
| 30 | + url: 'https://github.com/stevensacks/eslint-plugin-sort-react-dependency-arrays' |
| 31 | + }, |
| 32 | + schema: [] // no options |
| 33 | + }, |
| 34 | + create: function(context) { |
| 35 | + return { |
| 36 | + CallExpression(node) { |
| 37 | + if (isDependencyArrayHook(node.callee)) { |
| 38 | + const dependencies = node.arguments[1]; |
| 39 | + |
| 40 | + if (dependencies && dependencies.type === 'ArrayExpression' && dependencies.elements.length > 1) { |
| 41 | + const sorted = [...dependencies.elements].sort((a, b) => (a.name < b.name ? -1 : 1)); |
| 42 | + const sortedNames = sorted.map((dep) => dep.name); |
| 43 | + |
| 44 | + context.report({ |
| 45 | + node, |
| 46 | + message: 'Sorting dependencies', |
| 47 | + fix: function (fixer) { |
| 48 | + return fixer.replaceText(dependencies, `[${sortedNames}]`); |
| 49 | + } |
| 50 | + }); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + }; |
| 55 | + } |
| 56 | +}; |
0 commit comments