2017-06-05 73 views
0
// Input 
class Foo { 
    templateString = 'some value'; 
} 

// Output 
import __LIB__ from '@scope/lib/path/to/lib'; 

class Foo { 
    templateString = (function compiledTemplate(deps) { 
     // ... 
     return result; 
    })({lib: __LIB__}); 
} 

實際上在修改NodeArrays,我有兩個問題:插入任意文本和打字稿編譯器API

  1. 如何創建字符串AST片段?
  2. 如何添加導入?

P.S. I tried各種方法createSourceFilets.createImportDeclaration,但他們都帶來這樣或那樣的錯誤:[

+1

您是否嘗試過使用替換節點的適當文本創建標識符?換句話說:''createIdentifier('(function compiledTemplate(deps){/*...*/}')''。 –

+0

這是工作0_o ,但是如何在'@ scope/lib'中添加'import lib;'? – RubaXa

回答

1

要在任意文本中添加,我知道最好的辦法是使用createIdentifier與要插入的字符串。


要在import語句添加,請記住,您要更新樹突變原。

ts.visitEachChild API需要nodesVisitor參數,該參數專門用於NodeArray s。通常,如果您未通過nodesVisitor,它將在NodeArray中的每個Node上使用您爲visitor參數傳遞的第一個回調進行操作,但此處您特別要在整個節點陣列上進行操作。

在你的情況,你有興趣在SourceFile的語句(這是一個NodeArray<Statement>您可以createImportDeclaration創建導入,並通過在nodesVisitor通過類似下面的更新SourceFile

function addImport(statements: ts.NodeArray<ts.Statement>) { 
    const importStatement = ts.createImportStatement(/*...*/); 
    return ts.createNodeArray([importStatement, ...statements]); 
} 

visitEachChild(
    sourceFile, 
    /*replace this with something that controls traversal*/ x => x, 
    context, 
    addImport); 
+0

唉,不要工作:https://gist.github.com/RubaXa/5896badb923f0805aa9fcdc480afe9cc#file-x-danielros enwasser-ts – RubaXa

+0

查看我給出的關於如何創建新節點以及如何調用'visitEachChild'的示例。 –

+0

發生了,但仍然無法正常工作:https://github.com/RubaXa/typescript-api-questions/tree/master/import-add – RubaXa