When I generate my Typescript code using the compiler api's Printer
my code is generated as follows:
namespace Something {
export function foo() {
...
}
export function bar() {
...
}
}
namespace SomethingElse {
export function baz() {
...
}
}
For readability I want to generate extra empty lines between foo
↔bar
and Something
↔SomethingElse
. Is this possible using the typescript compiler api?
While I also could not find an official way to insert clean newlines or whitespace trivia, I solved the issue for me with inserting single line comments which allow then adding trailing newlines:
ts.addSyntheticTrailingComment(oldNode, ts.SyntaxKind.SingleLineCommentTrivia, '', true /*trailing newline*/)
ts.addSyntheticLeadingComment(oldNode, ts.SyntaxKind.SingleLineCommentTrivia, '', true /*trailing newline*/)
Note that this will also actually generate a single line comment which might not be desired for all scenarios. For use cases where you just want to have the generatated code a bit more readable the trailing comments work out nice.
An alternative workaround that is as close as it gets to simply inserting a newline between AST tree nodes is slightly misusing the createIdentifier
factory function. If one is using the compiler API to essentially pretty-print AST trees, this might be the best currently available option. Here is the trick:
ts.factory.createIdentifier("\n");
Then one can insert the identifier (or even several of them) after each node that needs to be separated before calling the Printer
methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With