使用 Typescript Compiler API 重写 typescript 文件
Using Typescript Compiler API to rewrite typescript file
我正在尝试使用 Typescript Compiler API 来创建一个用于合并 typescript 文件的工具。我想知道有没有办法:
- 解析 .ts 文件生成 AST 后更改。
- 序列化将 AST 改回 .ts 文件
我已阅读 documentation 关于编译器 API,但它似乎只涵盖了使用 AST 的只读用例,而我对修改源文件更感兴趣。
提前感谢您的帮助。
Change AST after it was produced by parsing .ts file.
Serialize changed AST back to .ts file
这两个都是发射器插件,你需要添加一个自定义transformer
。最好的文档仍在 PR https://github.com/Microsoft/TypeScript/pull/13940
这里是一个简单的例子,使用转换来遍历和转换 AST,并使用打印机将转换后的 AST 打印回另一个源文件:
这个很简单:
https://typescript-api-playground.glitch.me/#example=Simple%20Transformation
这比第一个稍微复杂一点:
https://typescript-api-playground.glitch.me/#example=Transformation%202
最后一个:https://typescript-api-playground.glitch.me/#example=Transformation%203
您可以再次修改并 运行 代码,并创建一个 URL 并在此处分享一个示例,以防您遇到困难。
还有一个更简单的编译器方法 API 可以是 ts-simple-ast 项目。
我正在尝试使用 Typescript Compiler API 来创建一个用于合并 typescript 文件的工具。我想知道有没有办法:
- 解析 .ts 文件生成 AST 后更改。
- 序列化将 AST 改回 .ts 文件
我已阅读 documentation 关于编译器 API,但它似乎只涵盖了使用 AST 的只读用例,而我对修改源文件更感兴趣。
提前感谢您的帮助。
Change AST after it was produced by parsing .ts file. Serialize changed AST back to .ts file
这两个都是发射器插件,你需要添加一个自定义transformer
。最好的文档仍在 PR https://github.com/Microsoft/TypeScript/pull/13940
这里是一个简单的例子,使用转换来遍历和转换 AST,并使用打印机将转换后的 AST 打印回另一个源文件:
这个很简单:
https://typescript-api-playground.glitch.me/#example=Simple%20Transformation
这比第一个稍微复杂一点:
https://typescript-api-playground.glitch.me/#example=Transformation%202
最后一个:https://typescript-api-playground.glitch.me/#example=Transformation%203
您可以再次修改并 运行 代码,并创建一个 URL 并在此处分享一个示例,以防您遇到困难。
还有一个更简单的编译器方法 API 可以是 ts-simple-ast 项目。