You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 11:57:58