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

如何通过TypeScript编译器提取函数节点的完整函数代码(含声明)?

提取TypeScript文件中的完整函数代码

要获取包含函数声明的完整代码,你需要利用TypeScript AST节点的getText()方法,传入对应的SourceFile对象就能拿到该节点的原始文本。另外,你的代码目前只处理了顶层函数,如果需要提取嵌套函数,还需要递归遍历AST节点。

修正后的代码

interface ExtractedFunction {
  funcName: string;
  funcBody: string;
}

export async function extract(file: string): Promise<ExtractedFunction[]> {
  const program = ts.createProgram([file], { allowJs: true });
  const sourceFile = program.getSourceFile(file);
  if (!sourceFile) return [];

  const output: ExtractedFunction[] = [];

  // 递归遍历所有节点,处理顶层和嵌套函数
  function traverseNode(node: ts.Node) {
    // 处理函数声明
    if (ts.isFunctionDeclaration(node)) {
      const funcName = node.name ? node.name.text : "<anonymous>";
      // 获取整个函数的完整代码(包含声明、参数、函数体)
      const funcFullCode = node.getText(sourceFile);
      output.push({ funcName, funcBody: funcFullCode });
    }

    // 递归处理子节点,提取嵌套函数
    ts.forEachChild(node, traverseNode);
  }

  traverseNode(sourceFile);
  return output;
}

关键说明

  • node.getText(sourceFile):TypeScript的AST节点自带这个方法,传入源文件对象后,会返回该节点对应的原始代码文本,正好满足你需要的「包含函数声明的完整函数代码」需求。
  • 递归遍历:原代码只处理了顶层的函数节点,新增的traverseNode函数会递归遍历所有子节点,这样能提取出嵌套在其他函数、类或块级作用域里的函数。
  • 类型定义:替换了any为明确的ExtractedFunction接口,让代码类型更安全。

如果只需要提取顶层函数,去掉递归逻辑即可,直接保留原有的ts.forEachChild(sourceFile, ...)结构,把获取文本的逻辑替换成node.getText(sourceFile)就行。

内容的提问来源于stack exchange,提问作者Haardik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 15:07:55