How can I parse, modify and repair AST in a TypeScript file (like jscodeshift)?
My use case: I am creating a Yeoman generator that modifies TypeScript files; similar to:
- Add
import
statements - Importing components into an AngularJS module
Yeoman recommends using the AST parser for this task:
The most reliable way to do this is to parse the AST (Abstract Syntax Tree) file and edit it.
Tools like jscodeshift make it pretty easy for JavaScript files, but don't seem to support TypeScript. Are there similar tools to parse and modify a TypeScript AST file?
source to share
ts-simple-ast
suits your needs?
import { Project } from "ts-simple-ast";
const project = new Project();
// ...lots of code here that manipulates, copies, moves, and deletes files...
const sourceFile = project.getSourceFile("Models/Person.ts");
const importDeclaration = sourceFile.addImportDeclaration({
defaultImport: "MyClass",
moduleSpecifier: "./file"
});
// when you're all done, call this and it will save everything to the file system
project.save();
https://github.com/dsherret/ts-simple-ast
https://dsherret.github.io/ts-simple-ast/
source to share
It looks like it jscodeshift
supports TypeScript ( ts
and tsx
) via option --parser
since v0.6.0 ( https://github.com/facebook/jscodeshift/releases/tag/v0.6.0 ).
source to share