Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Typescript Compiler API to rewrite typescript file

I'm trying to work with Typescript Compiler API to create a tool for merging typescript files. I'd like to know is there a way to:

  1. Change AST after it was produced by parsing .ts file.
  2. Serialize changed AST back to .ts file

I have read documentation on Compiler API, but it seems to cover only read-only uses-cases of working with AST, while I'm more interesting in modifying source files.

Thanks for any help in advance.

like image 638
execc Avatar asked May 07 '17 09:05

execc


1 Answers

Here a simple example using transformations to walk and transform the AST and Printer to print the transformed AST back to another source file:

this is very simple one:

https://typescript-api-playground.glitch.me/#example=Simple%20Transformation

This is another a little bit complex than first one:

https://typescript-api-playground.glitch.me/#example=Transformation%202

And a last one : https://typescript-api-playground.glitch.me/#example=Transformation%203

You can modify and run the code again and create a URL with an example too share here in case you get stuck .

Also an easier approach to compiler API could be ts-simple-ast project.

like image 136
cancerbero Avatar answered Sep 25 '22 06:09

cancerbero