如何通过TypeScript编译器API获取节点在原TS文件中的行号?
TypeScript编译器API获取节点原文件行号的方法
当然可以通过TypeScript编译器API获取节点在原TypeScript文件中的行号,而且你提供的report函数代码,本质上已经在做这件事了。
代码原理说明
node.getStart():获取当前AST节点在源文件中的起始字符偏移量(从文件开头开始计算的字符总数)sourceFile.getLineAndCharacterOfPosition(offset):将字符偏移量转换成对应原文件的行号和列号。代码里给line加1,是因为TypeScript内部行号从0开始计数,加1后就是我们日常使用的从1开始的行号格式。
如果需要获取节点结束位置的行号和列号,只需要把node.getStart()换成node.getEnd()即可,示例如下:
function reportNodeRange(node: ts.Node, message: string) { const startPos = node.getStart(); const endPos = node.getEnd(); const { line: startLine, character: startChar } = sourceFile.getLineAndCharacterOfPosition(startPos); const { line: endLine, character: endChar } = sourceFile.getLineAndCharacterOfPosition(endPos); console.log(`${sourceFile.fileName} 从(${startLine + 1},${startChar + 1})到(${endLine + 1},${endChar + 1}): ${message}`); }
内容的提问来源于stack exchange,提问作者Kavit Shah
相关产品推荐
相关产品推荐

