From 161317e664ff00e0c0a27f3d032613f621c05939 Mon Sep 17 00:00:00 2001 From: Chiawen Chen Date: Sun, 10 Apr 2022 21:54:20 +0800 Subject: [PATCH] [Refactor] improve performance for detecting class components --- CHANGELOG.md | 2 ++ lib/util/Components.js | 26 +++++++++++++++++++++----- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 10026c0a00..064c01ee75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,7 +21,9 @@ This change log adheres to standards from [Keep a CHANGELOG](https://keepachange * [Refactor] fix linter errors ([#3261][] @golopot) * [Docs] [`no-unused-prop-types`]: fix syntax errors ([#3259][] @mrdulin) * [Refactor] improve performance for detecting function components ([#3265][] @golopot) +* [Refactor] improve performance for detecting class components ([#3267][] @golopot) +[#3267]: https://github.com/yannickcr/eslint-plugin-react/pull/3267 [#3266]: https://github.com/yannickcr/eslint-plugin-react/pull/3266 [#3265]: https://github.com/yannickcr/eslint-plugin-react/pull/3265 [#3261]: https://github.com/yannickcr/eslint-plugin-react/pull/3261 diff --git a/lib/util/Components.js b/lib/util/Components.js index 1d89953a20..8db12a570a 100644 --- a/lib/util/Components.js +++ b/lib/util/Components.js @@ -259,20 +259,29 @@ function componentRule(rule, context) { const utils = { /** - * Check if the node is a React ES5 component + * Check if an ObjectExpression is a React ES5 component * * @param {ASTNode} node The AST node being checked. * @returns {Boolean} True if the node is a React ES5 component, false if not */ isES5Component(node) { - if (!node.parent) { + if (!node.parent || !node.parent.callee) { return false; } - return new RegExp(`^(${pragma}\\.)?${createClass}$`).test(sourceCode.getText(node.parent.callee)); + const callee = node.parent.callee; + // React.createClass({}) + if (callee.type === 'MemberExpression') { + return callee.object.name === pragma && callee.property.name === createClass; + } + // createClass({}) + if (callee.type === 'Identifier') { + return callee.name === createClass; + } + return false; }, /** - * Check if the node is a React ES6 component + * Check if a class is a React ES6 component * * @param {ASTNode} node The AST node being checked. * @returns {Boolean} True if the node is a React ES6 component, false if not @@ -285,7 +294,14 @@ function componentRule(rule, context) { if (!node.superClass) { return false; } - return new RegExp(`^(${pragma}\\.)?(Pure)?Component$`).test(sourceCode.getText(node.superClass)); + if (node.superClass.type === 'MemberExpression') { + return node.superClass.object.name === pragma + && /^(Pure)?Component$/.test(node.superClass.property.name); + } + if (node.superClass.type === 'Identifier') { + return /^(Pure)?Component$/.test(node.superClass.name); + } + return false; }, /**