[英]How do I add another property to an existing json object in a typescript file using typscript compiler?
I have the following file with me我有以下文件
const ServerURL = '';
export const URLConfig = {
ServerURL: ServerURL,
entityKeyUrl: ServerURL + '/path/to/resource/',
}
Now I want to add another url to this object using ast/typescript compiler apis.现在我想使用 ast/typescript 编译器 api 向这个 object 添加另一个 url。
What have I tried?我尝试了什么?
I have read the source file and extracted the text from the SourceFile but now I don't know how to update it with the new text.我已经阅读了源文件并从 SourceFile 中提取了文本,但现在我不知道如何使用新文本更新它。
Here is my code (hiding the other parts of the code)这是我的代码(隐藏代码的其他部分)
const source = getSourceFile(tree, '/path/to/serverurl.constants.ts');
const txt = source.getText();
const closingBrace = txt.lastIndexOf('};');
const aLineAboveClosingBrace = closingBrace - 2;
source.update("Hello", ts.createTextChangeRange(ts.createTextSpan(0, txt.length), "Hello".length + txt.length));
It results in an error "Debug failed, false expression".它会导致错误“调试失败,错误表达式”。 Can somebody guide me in this?
有人可以指导我吗?
Update 1 I have been able to do some string manipulation and been able to generate my text but now to be able to create a file, I used ts.createSourceFile
but that did not generate any file for me.更新 1我已经能够进行一些字符串操作并能够生成我的文本,但现在能够创建一个文件,我使用
ts.createSourceFile
但这并没有为我生成任何文件。
If you want to change it in compilation time, I'd suggest you use Transformation API to do that.如果您想在编译时更改它,我建议您使用 Transformation API 来做到这一点。
Currently TypeScript doesn't support to use custom transformers by using tsc
, but you can use tools like ttypescript .目前 TypeScript 不支持通过
tsc
使用自定义转换器,但您可以使用ttypescript 之类的工具。 See here to see what's the custom transformer should be like.请参阅此处以了解自定义转换器应该是什么样的。 Also, in the repo's readme you can find examples of other custom transformers (you can use one of them as your start point).
此外,在 repo 的自述文件中,您可以找到其他自定义转换器的示例(您可以使用其中一个作为起点)。
Another helpful tool you can use is ts-ast-viewer - it helps you see what the AST is and how to create the same (and then modify it) AST for the code.您可以使用的另一个有用工具是ts-ast-viewer - 它可以帮助您查看 AST 是什么以及如何为代码创建相同(然后修改它)AST。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.