我目前正在尝试使用 Typescript 的编译器 API 修改 FunctionDeclaration 的主体。我正在创建一些新的 VariableDeclarations,并且使用从 SourceFile A 派生的表达式来设置“初始化程序”字段。
然后,我尝试将这些新的 VariableDeclarations 添加到 SourceFile B 中的 FunctionDeclaration 主体中,但是当使用 SourceFile A 作为源文件时,这些新创建的 VariableDeclarations 的右侧无法正确打印printer.printFile(...)
。分号和运算符似乎可以打印,但没有标识符或文字。
问题似乎是不同的 SourceFiles,即使两个 SourceFiles 中使用的标识符完全相同。
有没有办法为那些新创建的 VariableDeclarations 设置 SourceFile (或者实际上为导致问题的“初始化程序”表达式)?如果没有,我还能做些什么来获取一个源文件中找到的表达式并在另一个源文件中使用它吗?
您无法将节点移动到不同的源文件,因为目前节点基本上是作为源文件文本的片段(跨度)实现的。
你所做的就是克隆它。
TypeScript Compiler API 的方式是实现 Transform。基本上它会遍历 AST,然后您确定要替换的节点,并返回一个新节点而不是原始节点。该转换会生成一个新的 sourceFile,然后您可以使用 ts.createPrinter 打印该文件。这些是一些工作示例(单击运行按钮,右侧的代码将被转换)
简单变换:https://typescript-api-playground.glitch.me/#example=Simple%20Transformation 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%202
另一个使用 ts.createMutableClone(),因此您只需克隆一个节点并仅编辑您需要的内容:https://typescript-api-playground.glitch.me/#example=Transformation%203 https://typescript-api-playground.glitch.me/#example=Transformation%203
(这是我制作的一个游乐场,你可以编辑并再次运行)
话虽这么说,我建议您查看这个库,它可能会让您定义表达式并将它们插入到几乎任何位置:https://github.com/dsherret/ts-morph https://github.com/dsherret/ts-morph
另外,如果您使用 ts.create*,这个项目对于自动转换这些表达式中的代码可能会有很大帮助:https://ts-creator.js.org/ https://ts-creator.js.org/
祝你好运
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)