如何解析、修改和重新生成 TypeScript 文件(如 jscodeshift)的 AST?

How can I parse, modify, and regenerate the AST of a TypeScript file (like jscodeshift)?

我的用例:我正在构建一个 Yeoman generator,用于修改 TypeScript 文件;方式类似于:

Yeoman 建议为此任务使用 AST 解析器:

The most reliable way to do so is to parse the file AST (abstract syntax tree) and edit it.

jscodeshift 等工具使 JavaScript 文件的操作变得相当简单,但它似乎不支持 TypeScript。是否有类似的工具来解析和修改 TypeScript 文件的 AST?

ts-simple-ast是否符合您的需求?

import { Project } from "ts-simple-ast";

const project = new Project();

// ...lots of code here that manipulates, copies, moves, and deletes files...
const sourceFile = project.getSourceFile("Models/Person.ts");
const importDeclaration = sourceFile.addImportDeclaration({
  defaultImport: "MyClass",
  moduleSpecifier: "./file"
});

// when you're all done, call this and it will save everything to the file system
project.save();

https://github.com/dsherret/ts-simple-ast

https://dsherret.github.io/ts-simple-ast/

https://dsherret.github.io/ts-simple-ast/setup/ast-viewers

https://dsherret.github.io/ts-simple-ast/manipulation/

看起来 jscodeshift 从 v0.6.0 (https://github.com/facebook/jscodeshift/releases/tag/v0.6.0) 开始通过 --parser 选项支持 TypeScript (ts, 和 tsx)。