Skip to content

Commit

Permalink
Update: no-unused-expression flags unused JSX
Browse files Browse the repository at this point in the history
React's createElement call is side-effect free, as are most JSX pragmas.
An unused JSX element indicates a logic error in the same way any unused, side-effect free expression is.
This extension the no-unused-expression rule flags unused JSX elements unless the (new) allowJsx configuration option is set
  • Loading branch information
duncanbeevers committed Jan 18, 2021
1 parent f7ca481 commit 7af0f6b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/rules/no-unused-expressions.js
Expand Up @@ -39,6 +39,10 @@ module.exports = {
{
type: "object",
properties: {
allowJsx: {
type: "boolean",
default: false
},
allowShortCircuit: {
type: "boolean",
default: false
Expand All @@ -63,6 +67,7 @@ module.exports = {

create(context) {
const config = context.options[0] || {},
allowJsx = config.allowJsx || false,
allowShortCircuit = config.allowShortCircuit || false,
allowTernary = config.allowTernary || false,
allowTaggedTemplates = config.allowTaggedTemplates || false;
Expand Down Expand Up @@ -140,6 +145,9 @@ module.exports = {
},
FunctionExpression: alwaysTrue,
Identifier: alwaysTrue,
JSXElement() {
return !allowJsx;
},
Literal: alwaysTrue,
LogicalExpression(node) {
if (allowShortCircuit) {
Expand Down
18 changes: 18 additions & 0 deletions tests/lib/rules/no-unused-expressions.js
Expand Up @@ -82,6 +82,17 @@ ruleTester.run("no-unused-expressions", rule, {
{
code: "obj?.foo(\"bar\")",
parserOptions: { ecmaVersion: 11 }
},

// JSX
{
code: "<div />",
options: [{ allowJsx: true }],
parserOptions: { ecmaFeatures: { jsx: true } }
},
{
code: "var partial = <div />",
parserOptions: { ecmaFeatures: { jsx: true } }
}
],
invalid: [
Expand Down Expand Up @@ -152,6 +163,13 @@ ruleTester.run("no-unused-expressions", rule, {
code: "obj?.foo().bar",
parserOptions: { ecmaVersion: 2020 },
errors: [{ messageId: "unusedExpression", type: "ExpressionStatement" }]
},

// JSX
{
code: "<div />",
parserOptions: { ecmaFeatures: { jsx: true } },
errors: [{ messageId: "unusedExpression", type: "ExpressionStatement" }]
}
]
});

0 comments on commit 7af0f6b

Please sign in to comment.