Refactor TypScript code programmatically using codemods
npm install ns-tsmod
npm install -g ns-tsmod
`
Please note that if you have never used TypeScript or ts-node you will also need them:
`
npm install -g typescript ts-node
`
The typescript module is the TypeScript compiler and the ts-node module is a version of Node.js that can work directly with TypeScript files (.ts) instead of using JavaScript files (.js).
Usage
The following command applies the transform var_to_const_transform.ts to the files fileA.ts and fileB.ts:
`sh
ns-tsmod -t var_to_const_transform.ts fileA.ts fileB.ts
`
> Please Note: A TypeScript compiler configuration file (tsconfig.json) file is expected in the current directory when you run the previous command.
Transform example
The transforms are powered by the ts-morph API. You can learn more about the API at https://ts-morph.com.
The following example changes all var variable declarations into const variable declarations:
`ts
import { SourceFile, SyntaxKind, VariableDeclarationKind } from "ts-morph";
export const varToConstTransform = (file: SourceFile, transformArgs: {}) => {
// Find all variable declarations in source file
const variableStatements = file.getDescendantsOfKind(
SyntaxKind.VariableStatement
);
// Change var for const for each statement
variableStatements.forEach(variableStatement => {
const declarationKind = variableStatement.getDeclarationKind();
if (declarationKind === VariableDeclarationKind.Var) {
variableStatement.setDeclarationKind(VariableDeclarationKind.Const);
}
});
// Return source code
const updatedSourceCode = file.getText();
return updatedSourceCode;
};
`
The code is represented using a data structure known as Abstract Syntax Tree (AST). You can navigate and modify the AST to generate updated code. You can visit https://ts-ast-viewer.com/ to visualize the AST if you need help navigating it.

Options
For additional help use the following:
`sh
ns-tsmod -h
``