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

mat*_*ele 6 yeoman typescript jscodeshift

我的用例:我正在构建一个Yeoman生成器,该生成器可以修改TypeScript文件。类似于:

  • 添加import语句
  • 将组件导入AngularJS模块

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

最可靠的方法是解析文件AST(抽象语法树)并对其进行编辑。

诸如jscodeshift之类的工具对于JavaScript文件而言相当简单,但它似乎不支持TypeScript。是否有任何类似的工具来解析和修改TypeScript文件的AST?

Sne*_*kse 4

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();
Run Code Online (Sandbox Code Playgroud)

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/