我的用例:我正在构建一个修改 TypeScript 文件的Yeoman 生成器;方式类似于:
- 添加import语句
- 将组件导入 AngularJS 模块
Yeoman 建议为此任务使用 AST 解析器:
最可靠的方法是解析文件 AST(抽象语法树)并对其进行编辑。
jscodeshift 之类的工具使 JavaScript 文件变得相当简单,但它似乎不支持 TypeScript。有没有类似的工具来解析和修改 TypeScript 文件的 AST?
我的用例:我正在构建一个修改 TypeScript 文件的Yeoman 生成器;方式类似于:
import语句Yeoman 建议为此任务使用 AST 解析器:
最可靠的方法是解析文件 AST(抽象语法树)并对其进行编辑。
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/
从 v0.6.0 ( https://github.com/facebook/jscodeshift/releases/tag/v0.6.0 ) 开始,它似乎通过选项jscodeshift支持 TypeScript ( ts, 和)。tsx--parser