-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathno-jsx-iife.js
More file actions
67 lines (63 loc) · 2.17 KB
/
no-jsx-iife.js
File metadata and controls
67 lines (63 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* Determines whether an expression is a directly invoked function expression inside JSX.
* @param {import('estree').Expression | import('estree').JSXEmptyExpression | null | undefined} expression - Expression to inspect.
* @returns
* - `true`: the expression is a `CallExpression` (including optional-call inside `ChainExpression`) whose callee is an arrow/function expression
* - `false`: the expression is anything else
* @example
* isImmediatelyInvokedFunctionExpression({
* type: 'CallExpression',
* callee: { type: 'ArrowFunctionExpression' },
* }) // => true
*/
function isImmediatelyInvokedFunctionExpression(expression) {
// Unwrap ChainExpression so optional-call IIFEs like `(() => 'x')?.()` are caught.
const target =
expression && expression.type === 'ChainExpression'
? expression.expression
: expression
return Boolean(
target &&
target.type === 'CallExpression' &&
(target.callee.type === 'ArrowFunctionExpression' ||
target.callee.type === 'FunctionExpression'),
)
}
export default {
meta: {
type: 'suggestion',
docs: {
description:
'Disallow immediately invoked function expressions inside JSX.',
category: 'Best Practices',
recommended: false,
url: 'https://github.com/laststance/react-next-eslint-plugin/blob/main/docs/rules/no-jsx-iife.md',
},
schema: [],
messages: {
noJsxIife:
'Do not use immediately invoked function expressions inside JSX. Move the logic outside JSX and reference the computed value instead.',
},
},
/**
* Creates rule listeners for JSX expression containers.
* @param {import('eslint').Rule.RuleContext} context - ESLint rule context.
* @returns
* - `RuleListener`: listeners that report directly invoked function expressions inside JSX
* @example
* create(context) // => { JSXExpressionContainer(node) { ... } }
*/
create(context) {
return {
JSXExpressionContainer(node) {
if (!isImmediatelyInvokedFunctionExpression(node.expression)) {
return
}
context.report({
node: node.expression,
messageId: 'noJsxIife',
})
},
}
},
}