Registry
Mmohebifar avatar

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.

mohebifar0 executions

  • javascript
  • typescript
  • template-literal
  • cleanup
Connect a repo
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
# Install from registry
npx codemod@latest javascript-prefer-template-literals

# Or run locally
npx codemod@latest workflow run -w .

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
'Hello, ' + 'world' + '!'
// ->
`Hello, ${'world'}!`

1 + '-' + 2 + '-' + 3
// ->
`${1}-${2}-${3}`

'count=' + (1 + 1)
// ->
`count=${1 + 1}`

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
npx codemod@latest workflow run -w . --param include_existing_templates=true

Development

bash
# Test the transformation
pnpm test

# Validate the workflow
npx codemod@latest workflow validate -w .

# Publish to registry
npx codemod@latest login
npx codemod@latest publish

License

MIT

Ready to evolve your codebase?

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