diff --git a/README.md b/README.md index 6a1c982..7f13511 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ The built-in configuration preset you get with `"extends": "tslint-react"` is se - Off by default - `jsx-self-close` (since v0.4.0) - Enforces that JSX elements with no children are self-closing. + - _Includes automatic code fix_ ```ts // bad
diff --git a/src/rules/jsxSelfCloseRule.ts b/src/rules/jsxSelfCloseRule.ts index 44e3a16..d3aaddf 100644 --- a/src/rules/jsxSelfCloseRule.ts +++ b/src/rules/jsxSelfCloseRule.ts @@ -50,7 +50,13 @@ function walk(ctx: Lint.WalkContext): void { && node.children[0].getText() === ""; const noChildren = node.children.length === 0 || textIsEmpty; - if (missingOpeningOrClosingTag || noChildren) { + if (!missingOpeningOrClosingTag && noChildren) { + const openingElementText = node.openingElement.getFullText(); + const selfClosingNode = openingElementText.slice(0, openingElementText.lastIndexOf(">")) + "/>"; + const fix = new Lint.Replacement(node.getStart(), node.getWidth(), selfClosingNode); + + ctx.addFailureAtNode(node, Rule.FAILURE_STRING, fix); + } else if (noChildren) { ctx.addFailureAtNode(node, Rule.FAILURE_STRING); } } diff --git a/test/rules/jsx-self-close/test.lint.fix b/test/rules/jsx-self-close/test.lint.fix new file mode 100644 index 0000000..245fc2b --- /dev/null +++ b/test/rules/jsx-self-close/test.lint.fix @@ -0,0 +1,27 @@ +
+ Contents +
+ + + + + + + + + +
diff --git a/test/rules/jsx-self-close/test.tsx.lint b/test/rules/jsx-self-close/test.tsx.lint index 41abdb2..a3e795c 100644 --- a/test/rules/jsx-self-close/test.tsx.lint +++ b/test/rules/jsx-self-close/test.tsx.lint @@ -10,6 +10,9 @@

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [JSX elements with no children must be self-closing] +

+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [JSX elements with no children must be self-closing] +