Search code examples
typescripttypescript-compiler-api

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?


Solution

  • 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.