Skip to content

Commit

Permalink
Add auto fixer for jsx-self-close-rule (#189)
Browse files Browse the repository at this point in the history
  • Loading branch information
QuentinBouygues authored and adidahiya committed Mar 13, 2019
1 parent 9d9a299 commit 61e2f50
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<div className="foo"></div>
Expand Down
8 changes: 7 additions & 1 deletion src/rules/jsxSelfCloseRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,13 @@ function walk(ctx: Lint.WalkContext<void>): 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);
}
}
Expand Down
27 changes: 27 additions & 0 deletions test/rules/jsx-self-close/test.lint.fix
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<div>
Contents
</div>



<span />

<button />



<h2 class="colouring" contents="B" />



<h2 class="html-content" content="<h1></h1>" />

<button onClick="run()" />

<button>
<div />
</button>



<div />
3 changes: 3 additions & 0 deletions test/rules/jsx-self-close/test.tsx.lint
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
<h2 class="colouring" contents="B"></h2>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [JSX elements with no children must be self-closing]

<h2 class="html-content" content="<h1></h1>"></h2>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [JSX elements with no children must be self-closing]

<button onClick="run()" />

<button>
Expand Down

0 comments on commit 61e2f50

Please sign in to comment.