Aalexbit-codemod

var-to-let-const

Convert var declarations to let or const based on reassignment analysis, preserving function-scoped behavior when variables are accessed outside block scope

varletconstmodernizationmigrationes6
Public
12 executions
2 stars
How to Use
Run this codemod on your codebase using one of the following commands

The easiest way to run this codemod without installing anything globally:

Documentation

var-to-let-const

Convert var declarations to let or const based on reassignment analysis, preserving function-scoped behavior when variables are accessed outside block scope.

Supported Use Cases and Patterns

This codemod intelligently converts var declarations to modern ES6+ syntax:

  • Basic conversions: Variables that are never reassigned become const; variables that are reassigned become let
  • Update expressions: Handles ++, --, +=, -=, and other compound assignments
  • Loop variables: Correctly identifies variables in for...in and for...of loops
  • Nested scopes: Analyzes variables independently within their respective scopes
  • Variable shadowing: Handles variables with the same name in different scopes correctly
  • Conditional assignments: Works with assignments inside if, switch, and ternary expressions
  • Complex expressions: Preserves object property and array index assignments without affecting variable declarations
  • TSX/React: Supports TypeScript and JSX syntax
  • Uninitialized variables: Converts var x; to let x; (since const requires initialization)
  • Function-scoped preservation: Safely skips conversion when var is accessed outside its block scope (preserving function-scoped behavior)

Example

Before:

typescript

After:

typescript

Enterprise Features

Enterprise customers get access to additional features and support:

  • Sharding by codeowner or directory: Efficiently process large codebases by splitting work across teams or code ownership boundaries
  • AI review and automated quality checks: Automated code review and quality assurance to ensure transformations maintain code quality and correctness
  • Pre and post run hooks: Customize the codemod workflow with pre-run validation and post-run verification steps
  • Priority support and updates: Get priority support for issues and early access to new features and improvements
  • Team training and onboarding: Comprehensive training and onboarding resources to help your team effectively use and maintain codemods
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.