Skip to content

Commit

Permalink
consistent-function-scoping: Ignore anything containing JSX (#382)
Browse files Browse the repository at this point in the history
  • Loading branch information
MrHen authored and sindresorhus committed Sep 18, 2019
1 parent b62d96e commit 8a999c0
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 13 deletions.
12 changes: 12 additions & 0 deletions docs/rules/consistent-function-scoping.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,15 @@ function doFoo(foo) {
return foo;
}
```

It also ignores functions that contain `JSXElement` references:

```jsx
function doFoo(FooComponent) {
function Bar() {
return <FooComponent/>;
}

return Bar;
};
```
44 changes: 31 additions & 13 deletions rules/consistent-function-scoping.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,30 +121,48 @@ const create = context => {
const sourceCode = context.getSourceCode();
const {scopeManager} = sourceCode;

const reports = [];
let hasJsx = false;

return {
ArrowFunctionExpression(node) {
ArrowFunctionExpression: node => {
const valid = checkNode(node, scopeManager);

if (valid) {
return;
reports.push(null);
} else {
reports.push({
node,
messageId: MESSAGE_ID_ARROW
});
}

context.report({
node,
messageId: MESSAGE_ID_ARROW
});
},
FunctionDeclaration(node) {
FunctionDeclaration: node => {
const valid = checkNode(node, scopeManager);

if (valid) {
return;
reports.push(null);
} else {
reports.push({
node,
messageId: MESSAGE_ID_FUNCTION
});
}
},
JSXElement: () => {
// Turn off this rule if we see a JSX element because scope
// references does not include JSXElement nodes.
hasJsx = true;
},
':matches(ArrowFunctionExpression, FunctionDeclaration):exit': () => {
const report = reports.pop();
if (report && !hasJsx) {
context.report(report);
}

context.report({
node,
messageId: MESSAGE_ID_FUNCTION
});
if (reports.length === 0) {
hasJsx = false;
}
}
};
};
Expand Down
32 changes: 32 additions & 0 deletions test/consistent-function-scoping.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ import rule from '../rules/consistent-function-scoping';
const ruleTester = avaRuleTester(test, {
env: {
es6: true
},
parserOptions: {
ecmaVersion: 2018,
ecmaFeatures: {
jsx: true
}
}
});

Expand Down Expand Up @@ -156,6 +162,32 @@ ruleTester.run('consistent-function-scoping', rule, {
doZaz('zaz');
};
`,
outdent`
function doFoo() {
return function doBar() {};
}
`,
outdent`
function doFoo(Foo) {
function doBar() {
return new Foo();
}
return doBar;
};
`,
outdent`
function doFoo(FooComponent) {
return <FooComponent />;
}
`,
outdent`
function doFoo(FooComponent) {
function Bar() {
return <FooComponent />;
}
return Bar;
};
`
],
invalid: [
Expand Down

0 comments on commit 8a999c0

Please sign in to comment.