如何使用 Typescript 编译器 API 打印机在节点之间生成额外的换行符

sup*_*key 10 typescript typescript-compiler-api

当我使用编译器 api 生成我的 Typescript 代码时,Printer我的代码生成如下:

namespace Something {
    export function foo() {
        ...
    }
    export function bar() {
        ...
    }
}
namespace SomethingElse {
    export function baz() {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

为了可读性,我想在foo? barSomethingSomethingElse. 这可以使用打字稿编译器api吗?

Ole*_*ter 5

另一种解决方法是简单地在 AST 树节点之间插入换行符,但稍微滥用了createIdentifier工厂函数。如果使用编译器 API 来本质上漂亮地打印 AST 树,这可能是当前可用的最佳选项。这是技巧:

ts.factory.createIdentifier("\n");
Run Code Online (Sandbox Code Playgroud)

然后,可以在调用方法之前在需要分隔的每个节点后面插入标识符(甚至多个标识符)Printer