From 639e7724f472ed2ed1cd9e1955519ba6705431a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arnaud=20Barr=C3=A9?= Date: Sat, 11 Jan 2025 21:06:30 +0100 Subject: [PATCH] Fix detection of local components to not generate warning on for variable inside JSX files that follow React component naming (fixes #75) --- CHANGELOG.md | 4 ++++ src/only-export-components.test.ts | 4 ++++ src/only-export-components.ts | 21 ++++++++++----------- 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61e8f6b..4e5aff8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased + +- Fix detection of local components to not generate warning on for variable inside JSX files that follow React component naming + ## 0.4.16 Fix CJS/ESM interop issue. Sorry everyone for the trouble. diff --git a/src/only-export-components.test.ts b/src/only-export-components.test.ts index 1bfc26a..df50af3 100755 --- a/src/only-export-components.test.ts +++ b/src/only-export-components.test.ts @@ -194,6 +194,10 @@ const valid = [ code: "const MyComponent = () => {}; export default observer(MyComponent);", options: [{ customHOCs: ["observer"] }], }, + { + name: "Local constant with component casing and non component function", + code: "const SomeConstant = 42; export function someUtility() { return SomeConstant }", + }, ]; const invalid = [ diff --git a/src/only-export-components.ts b/src/only-export-components.ts index a272abe..846ea99 100644 --- a/src/only-export-components.ts +++ b/src/only-export-components.ts @@ -99,15 +99,6 @@ export const onlyExportComponents: TSESLint.RuleModule< )[] = []; const reactContextExports: TSESTree.Identifier[] = []; - const handleLocalIdentifier = ( - identifierNode: TSESTree.BindingName, - ) => { - if (identifierNode.type !== "Identifier") return; - if (reactComponentNameRE.test(identifierNode.name)) { - localComponents.push(identifierNode); - } - }; - const handleExportIdentifier = ( identifierNode: TSESTree.BindingName | TSESTree.StringLiteral, isFunction?: boolean, @@ -264,10 +255,18 @@ export const onlyExportComponents: TSESLint.RuleModule< } } else if (node.type === "VariableDeclaration") { for (const variable of node.declarations) { - handleLocalIdentifier(variable.id); + if ( + variable.id.type === "Identifier" && + reactComponentNameRE.test(variable.id.name) && + canBeReactFunctionComponent(variable.init) + ) { + localComponents.push(variable.id); + } } } else if (node.type === "FunctionDeclaration") { - handleLocalIdentifier(node.id); + if (reactComponentNameRE.test(node.id.name)) { + localComponents.push(node.id); + } } else if ( node.type === "ImportDeclaration" && node.source.value === "react"