我读过“whole internet”,但找不到任何有关从 TypeScrypt 源获取语法树(就像在 Esprima 中一样)的示例。 我的意思是我怎样才能得到这样的对象(Esprima Parser 示例)
{
"type": "Program",
"body": [
{
"type": "VariableDeclaration",
"declarations": [
{
"type": "VariableDeclarator",
"id": {
"type": "Identifier",
"name": "answer"
},
"init": {
"type": "BinaryExpression",
"operator": "*",
"left": {
"type": "Literal",
"value": 6,
"raw": "6"
},
"right": {
"type": "Literal",
"value": 7,
"raw": "7"
}
}
}
],
"kind": "var"
}
]
}
来自javascript代码
var answer = 6 * 7;
仅适用于 TypeScript 源文本?
附言我非常希望得到你的帮助,因为我不想写你自己的糟糕自行车)
附言我认为 lib 文件 typescript.ts(.js) 和 typescriptServices.ts(.js) 可以帮助我,但我不知道如何:(
已解决
非常感谢用户 Steve Fenton。 这是我的代码,如果有人感兴趣的话:
// uses
var typeScriptLS = new Harness.TypeScriptLS();
var ServicesFactory = new Services.TypeScriptServicesFactory();
var serviceShim = ServicesFactory.createLanguageServiceShim(typeScriptLS);
// add lib.d.ts
var _libText = window.document.getElementById('lib.d.ts').innerText;
typeScriptLS.addScript('lib.d.ts', _libText.replace(/\r\n?/g,"\n"), true);
// add greeter.ts
var _sourceText = window.document.getElementById('greeter.ts').innerText;
typeScriptLS.addScript('greeter.ts', _sourceText.replace(/\r\n?/g,"\n"), true);
// script name
var _scriptName = 'greeter.ts';
// get syntax tree
var _st = serviceShim.languageService.getSyntaxTree(_scriptName);
//console.log(_st);
console.log(JSON.stringify(_st, "", 2));
最佳答案
TypeScript 解析器不会直接生成那样的树,但您仍然可以使用它的对象模型来做各种事情。例如,我们在某些工具中使用它来进行语法转换以进行测试。这是一个可用于打印语法树的片段:
import ts from "typescript";
const code = "enum { x = 1 }";
const sc = ts.createSourceFile("x.ts", code, ts.ScriptTarget.Latest, true);
let indent = 0;
function print(node: ts.Node) {
console.log(new Array(indent + 1).join(" ") + ts.SyntaxKind[node.kind]);
indent++;
ts.forEachChild(node, print);
indent--;
}
print(sc);
关于TypeScript:获取语法树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20187928/