Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can use compiler API to transform Typescript to Typescript?

I'd like to build a tool to perform transformations on typescript code and emit them as typescript (rather than javascript) as part of one-time upgrade path on an existing code base. Is this possible and if so, how? I've found no comprehensive and clear references on the compiler API. Any pointers to references or actual code would be appreciated.

like image 246
snort Avatar asked Jan 01 '23 00:01

snort


1 Answers

You could do the following:

  1. Parse all the source files using ts.createSourceFile—create an AST/ts.SourceFile for every file.
  2. Transform each source file using ts.transform. Provide this with your transforms to use.
  3. Use ts.createPrinter to create a printer and print out the transformed source files.
  4. Write the printed source files to the file system.

Some example code is in my answer here.

Alternative

An important point to note about the above solution is that when the printer prints an AST, it will print it with its own formatting in mind for the most part.

If you want to maintain formatting in the files, then you might want to do the following instead:

  1. Parse all the source files into ASTs (same as #1 above).
  2. Traverse all the ASTs and create a collection of file text changes to execute on the files. An example data structure you might want to build up could be similar to the one found in the compiler API—FileTextChanges.
  3. Manipulate the text directly based on these file text changes.
  4. Save the text for each file to the file system.

An example is in my answer here.

Alternative 2

Since you'll only be executing this once on the code base, you will probably save a lot of time by using my library ts-morph instead.

like image 108
David Sherret Avatar answered Apr 25 '23 21:04

David Sherret