0

私は、typecriptソースファイルからコメントを、好ましくは行番号で抽出したいと思います。私は、すべてのノードのテキストを印刷したとき、私はコメントが完全に破棄されたことを見ることができ、実際にはtypescriptコンパイラAPIを使用してASTのノードとしてコメントを取得することはできますか?

var program = ts.createProgram(files, { 
    target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS, removeComments: false 
}); 
ts.forEachChild(sourceFile, visit); 

function visit(node) { 
    if (node.kind == ts.SyntaxKind.SingleLineCommentTrivia){ 
     //print something 
    } 
    ts.forEachChild(node, visit); 
} 

:私はこのようにそれをやってみました。テスト用に使用した入力ソースコードは次のとおりです。

//test comment 
declare namespace myLib { 
    //another comment 
    function makeGreeting(s: string): string; 
    let numberOfGreetings: number; 
} 

答えて

1

コメントはノードとして取得することはできませんが、ソースファイルからコメントを取得することはできます。使用する関数はgetLeadingCommentRanges(text: string, pos: number)です。

私はこのようにそれを使用:

for(var sourceFile of program.getSourceFiles()){ 
     ts.forEachChild(sourceFile, visit); 
    } 

function visit(node: ts.Node){ 
    let comments = ts.getLeadingCommentRanges(sourceFile.getText(), node.getFullStart(); 
} 
関連する問題