TypeScript创建SourceFile的API:如何获取语法错误信息

5

如果没有Program,只有SourceFile,那么如何获取相同类型的信息?TypeScript API的Program具有getSyntacticDiagnostics方法以获取语法错误。

我通过创建SourceFile来实现。

function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
1个回答

4

记住,在 createSourceFile 中,fileName(字符串)参数是虚拟文件名。这个(字符串)文件名在使用 TypeScript 库时是全局使用的。

你需要知道的最重要的事情是 createProgram 方法上的文档注释所说的内容。一个程序是“SourceFile”和表示编译单元的“CompilerOptions”的不可变集合。作为第一个参数的createProgram方法需要一组字符串,它们是这个程序中使用的虚拟文件名列表。

如果您不理解前面两个理论段落,我认为示例中的注释会对您有所帮助。

// this is the real code of file. Use fs.readFile, fs.readFileSync or something other to load file real source code.
var code = "class 1X {}";

// I will use this virtual name to reference SourceFile while working with TypeScript API.
var virtualFileName = "aaa.ts";

// initialize SourceFile instance
var sf = ts.createSourceFile(virtualFileName, code, ts.ScriptTarget.ES5);

// Make program as collection of my one virtual file
var prog = ts.createProgram([virtualFileName], {});

// process response as you need.
console.log(prog.getSyntacticDiagnostics(sf));

如果您收到“无法读取未定义的属性'text'”的错误,则可能还需要将第四个参数(setParentNodes)添加到createSourceFile中,即ts.createSourceFile(virtualFileName,code,ts.ScriptTarget.ES5,true); - danvk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接