api - 用于创建源文件的 TypeScript API : how to get syntactic errors information

标签 api typescript syntax-error

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/

相关文章:

c# - ServiceStack REST 服务中的自定义异常处理

api - 使用 HTTP DELETE 方法取消正在进行的操作

Mysql语法似乎正确

python - Python-嵌套迭代的语法错误?

c++ - GetExtendedUdpTable 和 netstat 结果之间的区别

api - RSPEC - PUT 请求返回错误 405

Angular 6 - 隐藏或显示从服务触发的组件中的 Div

typescript - 流 - 只能由函数产生的类型

javascript - 获取包含无效 css 的样式属性的完整值

Python 字符串/参数操作