2

我有一个 TypeScript 代码生成场景,我在其中构造了一个 AST,然后将其打印并保存到一个文件中。例如,打印的类声明元素聚集在一起。怎样才能实现在新方法/构造函数声明之后插入换行符的漂亮打印类型,并且也许可以在新行中堆叠扩展方法?

private baseUrl = "api/students";
constructor(private http: Http) { }
list(): Promise<Student[]> {
    return this.http.get(this.baseUrl + "/").toPromise().then((response: Response) => response.json()).catch(this.handleError);
}
get(id: number): Promise<Student> {
    return this.http.get(this.baseUrl + ("/" + id)).toPromise().then((response: Response) => response.json()).catch(this.handleError);
}

任何现有的 API 就足够了,或者有没有办法在声明后手动插入一些尾随琐事?

4

1 回答 1

3

格式化 API 将对此有所帮助:

const languageService: ts.LanguageService = ...;
const sourceFile: ts.SourceFile = ...;
const filePath: string = ...;

const textChanges = languageService.getFormattingEditsForDocument(filePath, {
    convertTabsToSpaces: true,
    insertSpaceAfterCommaDelimiter: true,
    insertSpaceAfterKeywordsInControlFlowStatements: true,
    insertSpaceBeforeAndAfterBinaryOperators: true,
    newLineCharacter: "\n",
    indentStyle: ts.IndentStyle.Smart,
    indentSize: 4,
    tabSize: 4
});

let finalText = sourceFile.getFullText();

for (const textChange in textChanges.sort((a, b) => b.span.start - a.span.start)) {
    const {span} = textChange;
    finalText = finalText.slice(0, span.start) + textChange.newText
        + finalText.slice(span.start + span.length);
}

// finalText contains the formatted text

也就是说,您可能想查看tsfmt它将为您执行此操作。

于 2017-12-08T02:24:36.350 回答