有没有办法从打字稿编译器 API 获取节点的行号?

Rab*_*bee 6 static-analysis abstract-syntax-tree typescript typescript-compiler-api

我知道我们可以使用获取节点的位置,node.pos但是有没有办法获取节点的行号?像node.lineNumber什么?

小智 8

let { line, character } = 
sourceFile.getLineAndCharacterOfPosition(node.getStart());
    console.log(`${sourceFile.fileName} (${line + 1},${character + 1}): 
${message}`);
Run Code Online (Sandbox Code Playgroud)

从这里:

https://github.com/Microsoft/TypeScript-wiki/blob/master/Using-the-Compiler-API.md

  • 请注意,根据“node”的创建方式,您可能需要将“sourceFile”传递给“node.getStart”,否则您将收到“无法读取未定义的属性“文本””之类的错误 (3认同)