Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
consistent-function-scoping: Ignore IIFE (#707)
  • Loading branch information
fisker committed May 3, 2020
1 parent b4779a7 commit 1f4413d
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 1 deletion.
20 changes: 20 additions & 0 deletions docs/rules/consistent-function-scoping.md
Expand Up @@ -71,3 +71,23 @@ function doFoo(FooComponent) {
return Bar;
};
```

[Immediately invoked function expressions (IIFE)](https://en.wikipedia.org/wiki/Immediately_invoked_function_expression) are ignored:

```js
(function () {
function doFoo(bar) {
return bar;
}
})();
```

[Built-in Hooks in React](https://reactjs.org/docs/hooks-reference.html) are ignored:

```js
useEffect(() => {
async function getItems() {}

getItems();
}, [])
```
16 changes: 15 additions & 1 deletion rules/consistent-function-scoping.js
Expand Up @@ -98,6 +98,15 @@ const isArrowFunctionWithThis = scope =>
scope.block.type === 'ArrowFunctionExpression' &&
(scope.thisFound || scope.childScopes.some(scope => isArrowFunctionWithThis(scope)));

const iifeFunctionTypes = new Set([
'FunctionExpression',
'ArrowFunctionExpression'
]);
const isIife = node => node &&
iifeFunctionTypes.has(node.type) &&
node.parent &&
node.parent.type === 'CallExpression';

function checkNode(node, scopeManager) {
const scope = scopeManager.acquire(node);

Expand Down Expand Up @@ -126,7 +135,12 @@ function checkNode(node, scopeManager) {
}

const parentScope = scopeManager.acquire(parentNode);
if (!parentScope || parentScope.type === 'global' || isReactHook(parentScope)) {
if (
!parentScope ||
parentScope.type === 'global' ||
isReactHook(parentScope) ||
isIife(parentNode)
) {
return true;
}

Expand Down
43 changes: 43 additions & 0 deletions test/consistent-function-scoping.js
Expand Up @@ -226,6 +226,37 @@ ruleTester.run('consistent-function-scoping', rule, {
function foo() {}
}, [])
`,
// IIEF
outdent`
(function() {
function bar() {}
})();
`,
outdent`
(function() {
function bar() {}
}());
`,
outdent`
!function() {
function bar() {}
}();
`,
outdent`
(() => {
function bar() {}
})();
`,
outdent`
(async function() {
function bar() {}
})();
`,
outdent`
(async function * () {
function bar() {}
})();
`,
// #391
outdent`
const enrichErrors = (packageName, cliArgs, f) => async (...args) => {
Expand Down Expand Up @@ -472,6 +503,18 @@ ruleTester.run('consistent-function-scoping', rule, {
}, [])
`,
errors: [createError({name: 'bar'})]
},
// IIFE
{
code: outdent`
(function() {
function foo() {
function bar() {
}
}
})();
`,
errors: [createError({name: 'bar'})]
}
]
});
Expand Down

0 comments on commit 1f4413d

Please sign in to comment.