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

如何通过TypeScript解析器从AST生成代码?escodegen报错求解

解决TypeScript AST转代码的报错问题

你遇到的Unknown node type: undefined错误,核心原因是escodegen 只支持 ESTree 规范的 AST(比如 Esprima、Acorn 生成的结构),但 TypeScript Compiler API 生成的 AST 是它自己独有的格式,两者节点结构和类型定义完全不兼容,所以直接用 escodegen 处理 TS AST 肯定会报错。

下面给你两种可行的解决办法:

方法一:使用 TypeScript 内置的 Printer API(推荐)

TypeScript 本身就提供了将 AST 转回代码的工具,也就是ts.createPrinter(),它完美适配自己生成的 AST,不需要额外转换,是最可靠的方案。

修改你的代码如下:

import * as fs from "fs";
import * as ts from "typescript";

const code = ` function foo() { } `;
// 创建TS的SourceFile节点
const node = ts.createSourceFile("x.ts", code, ts.ScriptTarget.Latest);

// 使用TS内置的Printer生成代码
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
const generatedCode = printer.printNode(ts.EmitHint.Unspecified, node, node);

console.log({ generatedCode });

运行这段代码后,就能正确输出格式化后的函数代码了。

方法二:将TS AST转换为ESTree格式后用escodegen处理

如果你一定要用 escodegen,可以借助@typescript-eslint/typescript-estree库,它能把 TypeScript 的 AST 转换成 ESTree 兼容的结构,这样 escodegen 就能识别处理了。

首先安装依赖:

npm install @typescript-eslint/typescript-estree escodegen

然后修改代码:

import * as fs from "fs";
import escodegen from "escodegen";
import * as ts from "typescript";
import { parse } from "@typescript-eslint/typescript-estree";

const code = ` function foo() { } `;
// 用typescript-estree解析代码得到ESTree规范的AST
const estreeAST = parse(code, {
  tsconfigRootDir: process.cwd(),
  project: "./tsconfig.json", // 如果项目没有tsconfig,可删除该配置项
});

// 用escodegen生成代码
const generatedCode = escodegen.generate(estreeAST);

console.log({ generatedCode });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:47:35