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
You could do the following:
- Parse all the source files using
ts.createSourceFile—create an AST/ts.SourceFilefor every file. - Transform each source file using
ts.transform. Provide this with your transforms to use. - Use
ts.createPrinterto create a printer and print out the transformed source files. - 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:
- Parse all the source files into ASTs (same as #1 above).
- 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. - Manipulate the text directly based on these file text changes.
- 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.
1 Comment
snort
Interesting. I really appreciate the detailed response and having some alternatives-- your lib looks very useful if I don't get into weird cases.