![](/img/trans.png)
[英]How to add assignment property to existing object literal expression in typescript compiler api?
[英]How do I add another property to an existing json object in a typescript file using typscript compiler?
我有以下文件
const ServerURL = '';
export const URLConfig = {
ServerURL: ServerURL,
entityKeyUrl: ServerURL + '/path/to/resource/',
}
現在我想使用 ast/typescript 編譯器 api 向這個 object 添加另一個 url。
我嘗試了什么?
我已經閱讀了源文件並從 SourceFile 中提取了文本,但現在我不知道如何使用新文本更新它。
這是我的代碼(隱藏代碼的其他部分)
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));
它會導致錯誤“調試失敗,錯誤表達式”。 有人可以指導我嗎?
更新 1我已經能夠進行一些字符串操作並能夠生成我的文本,但現在能夠創建一個文件,我使用ts.createSourceFile
但這並沒有為我生成任何文件。
如果您想在編譯時更改它,我建議您使用 Transformation API 來做到這一點。
目前 TypeScript 不支持通過tsc
使用自定義轉換器,但您可以使用ttypescript 之類的工具。 請參閱此處以了解自定義轉換器應該是什么樣的。 此外,在 repo 的自述文件中,您可以找到其他自定義轉換器的示例(您可以使用其中一個作為起點)。
您可以使用的另一個有用工具是ts-ast-viewer - 它可以幫助您查看 AST 是什么以及如何為代碼創建相同(然后修改它)AST。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.