Skip to content

Commit

Permalink
fix: handle nested conditions
Browse files Browse the repository at this point in the history
  • Loading branch information
gajus committed Jul 19, 2023
1 parent 000a680 commit 10ed0a0
Show file tree
Hide file tree
Showing 8 changed files with 59 additions and 14 deletions.
43 changes: 30 additions & 13 deletions src/rules/preferReactLazy.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
import { type TSESTree } from '@typescript-eslint/utils';
import { createRule } from '../utilities';

type Options = [];

type MessageIds = 'preferReactLazy';

const findConditionalExpressionParent = (node: TSESTree.JSXOpeningElement) => {
let currentNode: TSESTree.Node = node;

while (currentNode.parent) {
currentNode = currentNode.parent;

if (currentNode.type === 'ConditionalExpression') {
return true;
}
}

return false;
};

export default createRule<Options, MessageIds>({
create: (context) => {
const imported: string[] = [];

return {
ConditionalExpression(node) {
if (node.consequent.type === 'JSXElement') {
// @ts-expect-error TODO
const name = node.consequent.openingElement.name.name;

if (imported.includes(name)) {
context.report({
messageId: 'preferReactLazy',
node,
});
}
}
},
ImportDeclaration(node) {
for (const specifier of node.specifiers) {
if (specifier.type !== 'ImportSpecifier') {
Expand All @@ -31,6 +33,21 @@ export default createRule<Options, MessageIds>({
imported.push(specifier.imported.name);
}
},
JSXOpeningElement(node) {
// @ts-expect-error TODO
const name = node.name.name;

if (!findConditionalExpressionParent(node)) {
return;
}

if (imported.includes(name)) {
context.report({
messageId: 'preferReactLazy',
node,
});
}
},
};
},
defaultOptions: [],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import React from 'react';
import { Foo } from './Foo';

export default () => {
return <>
{Math.random() > 0.5 ? <Foo /> : null}
</>;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const Foo = () => {
return null;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import React from 'react';
import { Foo } from './Foo';

export default () => {
return <>
{Math.random() > 0.5 ? <div>
<Foo />
</div> : null}
</>;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const Foo = () => {
return null;
};
6 changes: 5 additions & 1 deletion tests/rules/preferReactLazy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ const validTest = (name: string, only: boolean = false) => {
};

ruleTester.run('prefer-react-lazy', rule, {
invalid: [invalidTest('staticImport')],
invalid: [
invalidTest('jsxConditionalExpression'),
invalidTest('nestedJsxConditionalExpression'),
invalidTest('returnConditionalExpression'),
],
valid: [validTest('dynamicImport')],
});

0 comments on commit 10ed0a0

Please sign in to comment.