2017-05-14 12 views
2

私はASTを作成し、それを印刷してファイルに保存するタイプスクリプトコード生成シナリオを持っています。たとえば、印刷されたクラス宣言要素は、一緒にクラスタ化されます。新しいメソッド/コンストラクタ宣言の後に改行を挿入し、おそらく新しいメソッドに拡張メソッドを積み重ねることができる、きれいな印刷のタイプを実現するにはどうすればよいでしょうか?TypeScriptコンパイラAPIで印刷コードを書式設定

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はどれでもかまいませんし、宣言後に手作業で挿入する方法もありますか?これで役立つ

+0

このファイルをどのように生成しますか?私はASTに白い文字を挿入できると思います。 'ts.SyntaxKind.NewLineTrivia'と' ts.SyntaxKind.WhitespaceTrivia'を参照してください。 – Misaz

答えて

0

の書式設定API:、あなたはあなたのためにこれを行いますtsfmtをチェックアウトする場合があります言わ

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 

関連する問題