【问题标题】:How to covert object literal AST of TypeScript file to Actual Code?如何将 TypeScript 文件的对象文字 AST 转换为实际代码?
【发布时间】:2018-08-30 14:58:49
【问题描述】:

我需要将 JSON 或 Object Literal 文件转换为实际代码。怎么做?

const astInJson = {"pos":0,"end":79,"flags":0,"kind":268,"text":"export interface Order {\n\torderId: string;\n\titineraries(id: string): string;\n}\n","bindDiagnostics":[],"languageVersion":5,"fileName":"/Users/myth/Desktop/test-interface.ts","languageVariant":0,"isDeclarationFile":false,"scriptKind":3,"referencedFiles":[],"typeReferenceDirectives":[],"amdDependencies":[],"statements":[{"pos":0,"end":78,"flags":0,"kind":230,"modifiers":[{"pos":0,"end":6,"flags":0,"kind":84}],"name":{"pos":16,"end":22,"flags":0,"escapedText":"Order"},"members":[{"pos":24,"end":42,"flags":0,"kind":148,"name":{"pos":24,"end":33,"flags":0,"escapedText":"orderId"},"type":{"pos":34,"end":41,"flags":0,"kind":136}},{"pos":42,"end":76,"flags":0,"kind":150,"name":{"pos":42,"end":55,"flags":0,"escapedText":"itineraries"},"parameters":[{"pos":56,"end":66,"flags":0,"kind":146,"name":{"pos":56,"end":58,"flags":0,"escapedText":"id"},"type":{"pos":59,"end":66,"flags":0,"kind":136}}],"type":{"pos":68,"end":75,"flags":0,"kind":136}}],"modifierFlagsCache":536870913}],"endOfFileToken":{"pos":78,"end":79,"flags":0,"kind":1},"externalModuleIndicator":{"pos":0,"end":78,"flags":0,"kind":230,"modifiers":[{"pos":0,"end":6,"flags":0,"kind":84}],"name":{"pos":16,"end":22,"flags":0,"escapedText":"Order"},"members":[{"pos":24,"end":42,"flags":0,"kind":148,"name":{"pos":24,"end":33,"flags":0,"escapedText":"orderId"},"type":{"pos":34,"end":41,"flags":0,"kind":136}},{"pos":42,"end":76,"flags":0,"kind":150,"name":{"pos":42,"end":55,"flags":0,"escapedText":"itineraries"},"parameters":[{"pos":56,"end":66,"flags":0,"kind":146,"name":{"pos":56,"end":58,"flags":0,"escapedText":"id"},"type":{"pos":59,"end":66,"flags":0,"kind":136}}],"type":{"pos":68,"end":75,"flags":0,"kind":136}}],"modifierFlagsCache":536870913},"nodeCount":15,"identifierCount":5,"identifiers":{},"parseDiagnostics":[]}

【问题讨论】:

  • 至少在这种情况下,看起来最外面的text属性有源代码。您想要源代码还是要将代码作为模块对象加载到当前 JavaScript 运行时中?
  • @MattMcCutchen 是的,在文本属性中它存在。但我不想用那个。我想更改对象文字中的一些属性,它应该给我数据作为 Typescript 源代码。简而言之,我需要 JSON 到 Typescript。

标签: typescript babeljs abstract-syntax-tree babylonjs transpiler


【解决方案1】:

如果你有一个ts.SourceFile 对象,你可以使用:

ts.createPrinter().printFile(file)

返回一个字符串。 ts.SourceFile 是一个包含循环引用的数据结构;如果您有一些字段子集作为 JSON,我不知道是否有任何合理的方法可以将其转换回 ts.SourceFile。更多想法可以关注the API to modify and print ASTs that is used by TypeScript's own code fixes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2019-03-11
    • 1970-01-01
    • 2021-05-18
    • 2018-09-12
    相关资源
    最近更新 更多