Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate extra newlines between nodes with the Typescript compiler API printer

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 foobar and SomethingSomethingElse. Is this possible using the typescript compiler api?

like image 821
superbadcodemonkey Avatar asked Mar 19 '19 17:03

superbadcodemonkey


2 Answers

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.

like image 122
Danielku15 Avatar answered Nov 19 '22 08:11

Danielku15


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.

like image 1
Oleg Valter is with Ukraine Avatar answered Nov 19 '22 09:11

Oleg Valter is with Ukraine