Mmohebifar

javascript-prefer-template-literals

Replace `+`-based string concatenation with template literals (backticks) in JavaScript/TypeScript code where semantics are preserved, aligning with ESLint `prefer-template` best practices and improving readability/maintainability.

javascripttypescripttemplate-literalcleanup
Public
0 executions

Run locally

npx codemod javascript-prefer-template-literals

javascript-prefer-template-literals

Replace +-based string concatenation with template literals (backticks) in JavaScript/TypeScript code where semantics are preserved, aligning with ESLint prefer-template best practices and improving readability/maintainability.

Installation

bash

Usage

This codemod rewrites left-associative + string-concatenation chains into template literals across:

  • .js, .mjs, .cjs, .ts via the TypeScript parser
  • .jsx, .tsx via the TSX parser

It transforms chains only when string intent is explicit and evaluation order is preserved.
It is intentionally conservative about chains whose first explicit string appears later in the expression.

Examples:

js

Preserve/no-op cases:

  • Pure arithmetic stays unchanged: a + b, 1 + 2 + 3
  • Ambiguous leading arithmetic stays unchanged: foo + bar + ' baz'
  • Safe-but-late string intent is still skipped conservatively: 1 + 2 + 'x'
  • Unknown object-like operands stay unchanged: 'a' + obj, obj + 'a'
  • Chains with interleaved comments stay unchanged
  • Parenthesized operands with inline comments stay unchanged
  • Chains already containing template literals stay unchanged by default
  • Nested parenthesized + chains are rewritten conservatively

To also merge chains that already contain template literals, run the workflow with:

bash

Development

bash

License

MIT

Before

This is one example from the codemod's test cases. The codemod may handle many more cases.

Ready to contribute?

Build your own codemod and share it with the community.