Registry
Mmohebifar avatar

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.

mohebifar0 executions

  • javascript
  • typescript
  • tsx
  • eslint
  • no-lonely-if
  • cleanup
Connect a repo
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
if (cond1) {
  stmt1();
} else {
  if (cond2) {
    stmt2();
  }
}

After:

js
if (cond1) {
  stmt1();
} else if (cond2) {
  stmt2();
}

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
pnpm dlx codemod@latest workflow run -w . -t /path/to/project --no-interactive

Override the ignore pragma at runtime:

bash
pnpm dlx codemod@latest workflow run -w . -t /path/to/project --no-interactive --param ignore_pragma="custom pragma"

Development

bash
pnpm test
pnpm dlx codemod@latest workflow validate -w .
pnpm dlx codemod@latest workflow run -w . -t /path/to/project --no-interactive

License

MIT

Ready to evolve your codebase?

Build tailored, compiler-aware skills to assess, plan, and automate complex codebase changes.