How can I parse, modify, and regenerate the AST of a TypeScript file (like jscodeshift)?
Asked Answered
B

2

9

My use case: I'm building a Yeoman generator, that modifies TypeScript files; in ways similar to:

  • Add import statements
  • Import components into an AngularJS module

Yeoman recommends using an AST parser for this task:

The most reliable way to do so is to parse the file AST (abstract syntax tree) and edit it.

Tools like jscodeshift make this fairly straightforward for JavaScript files, but it doesn't appear to support TypeScript. Are there any similar tools to parse and modify the AST of a TypeScript file?

Barrows answered 2/8, 2017 at 17:2 Comment(3)
See #40513648Krystakrystal
TSLint builds on the TSC and allows you to write rules and "fixers" to modify to the code, might be useful.Bisexual
What you are asking to do is possible with my library: ts-simple-astAndreaandreana
F
4

Does ts-simple-ast fit 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/

https://dsherret.github.io/ts-simple-ast/setup/ast-viewers

https://dsherret.github.io/ts-simple-ast/manipulation/

Fipple answered 31/10, 2018 at 16:27 Comment(1)
Between things like this and the raw TypeScript Compiler API, I think there are a few options. youtube.com/watch?v=CTpKZgy0dpoBarrows
B
2

It looks like jscodeshift supports TypeScript (ts, and tsx) via --parser option since v0.6.0 (https://github.com/facebook/jscodeshift/releases/tag/v0.6.0).

Birthday answered 15/10, 2019 at 15:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.