TypeScript API Program
有方法 getSyntacticDiagnostics
来获取语法错误。但是如果没有Program
,只有SourceFile
我怎么能得到同样的信息呢?
我通过
创建了SourceFile
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
最佳答案
请记住,createSourceFile 中的 fileName
(字符串)参数是虚拟文件名。此文件名(字符串)在使用 TypeScript 库时全局使用。
您需要的最重要的是 createProgam
方法上的文档注释。 程序是“SourceFile”和代表编译单元的“CompilerOptions”的不可变集合。 createProgam
方法作为第一个参数需要字符串列表,这些字符串是所用文件的虚拟名称在这个程序中。
如果您不理解前 2 个理论段落,我认为示例中的评论会对您有所帮助。
// 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));
关于api - 用于创建源文件的 TypeScript API : how to get syntactic errors information,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45233386/