Mmohebifar

javascript-eslint-no-lonely-if

Rewrite eligible JavaScript-family else blocks whose only statement is an if into else-if chains, matching ESLint no-lonely-if without changing behavior.

javascripttypescripttsxeslintno-lonely-ifcleanup
Public
0 executions

Run locally

npx codemod javascript-eslint-no-lonely-if

javascript-eslint-no-lonely-if

Normalize JavaScript-family else { if (...) ... } blocks into else if (...) ... chains when the else block contains only that nested if, matching ESLint's no-lonely-if intent without changing runtime behavior.

What It Rewrites

Before:

js

After:

js

The codemod also normalizes nested chains in one run, so else { if (...) ... else { if (...) ... } } becomes a flat else if chain.

Scope

  • Targets .js, .jsx, .mjs, .cjs, .ts, and .tsx
  • Preserves inner else branches
  • Preserves comments around the removed else block and inner if
  • Preserves multiline literal contents by keeping inner branch text intact instead of reindenting it
  • Skips files under dist/**, build/**, vendor/**, and *.min.*
  • Skips files containing codemod:ignore no-lonely-if by default

No-Op Cases

  • else blocks with more than one non-comment statement
  • else blocks whose single statement is not an if
  • if statements without an else
  • Code already written as else if
  • Excluded or pragma-marked files
  • Files with syntax errors are skipped by the codemod and reported with a diagnostic

Usage

bash

Override the ignore pragma at runtime:

bash

Development

bash

License

MIT

Ready to contribute?

Build your own codemod and share it with the community.