8

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.

1 Answer 1

16

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Interesting. I really appreciate the detailed response and having some alternatives-- your lib looks very useful if I don't get into weird cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.