【问题标题】:Detecting success/failure with Typescript watcher Compiler API使用 Typescript watcher Compiler API 检测成功/失败
【发布时间】:2019-07-23 22:44:43
【问题描述】:

Typescript 编译器 API 允许通过使用 ts.createWatchCompilerHost API 以编程方式创建手表编译器,Typescript 文档 here 中演示了它的使用示例。

此 API 接受回调作为其最后一个参数,该参数将在手表状态更改时调用,并提供一个描述手表状态更改的 Diagnostic 对象。

使用这些诊断事件,我试图区分compilingsuccessfailure 状态。我已经检测到compiling 状态工作正常,但是在确定successfailure 之间的区别时遇到了一个奇怪的问题。

我遇到的问题是由于诊断代码的应用如下。如果构建时出现 1 个错误,则提供代码 6193,否则提供代码 6194。这意味着如果没有错误(success)或有 2 个以上错误(failure),则提供代码 6194。这个逻辑可以在ts编译器here看到。

createWatchCompilerHost 的用户在构建时没有错误的情况和构建时出现 1+ 个错误的情况之间确定的预期方式是什么?

一个 hacky 解决方案是解析 diagnostic.messageText 以检查 Found 0 errors. 但这似乎非常脆弱,并且是我希望避免的解决方案。

【问题讨论】:

  • 很奇怪,0 错误和 2+ 错误的诊断代码相同。编译器中的代码对我来说看起来不正确,但它已经完成了几次,所以也许它是正确的。你可能想在 typescript repo 中打开一个关于这个的问题,看看他们怎么说。
  • 如果有人来这里想知道同样的事情,我已经在 github 上针对 typescript repo 提出了一个问题:Issue Link

标签: typescript typescript-compiler-api


【解决方案1】:

TS 3.7

在 TypeScript 3.7 中,errorCount 上现在有一个 errorCount 参数:

function reportWatchStatusChanged(
    diagnostic: Diagnostic,
    newLine: string,
    options: CompilerOptions,
    // I'm not sure why this is nullable, I am asking in the issue
    errorCount?: number
) {
    // check error count here
}

TS 3.7 之前的版本

鉴于示例中的以下监视主机:

const host = ts.createWatchCompilerHost(
  configPath,
  {},
  ts.sys,
  createProgram,
  reportDiagnostic,
  reportWatchStatusChanged
);

您可以添加一个由reportDiagnostic 回调触发的标志,然后在reportWatchStatusChanged 中检查并重置该标志。

例如:

let hadDiagnostics = false;

function reportDiagnostic(diagnostic: ts.Diagnostic) {
  hadDiagnostics = true;
  // ...etc...
}

function reportWatchStatusChanged(diagnostic: ts.Diagnostic) {
  if (hadDiagnostics) {
      console.log("Failed.");
      hadDiagnostics = false;
  } else {
      console.log("Success.");
  }

  // ...etc...
}

【讨论】:

  • 我想过这个问题,但我唯一担心的是是否有某种类型的报告 Diagnostic 实际上并不代表真正的错误。传递给reportDiagnostic 的每个Diagnostic 是否代表一些实际错误?
  • @casieber 是的。我只是查看了源代码以确认它们都将是实际错误(请参阅reportDiagnostic 如何称为here)。正如您在问题中提到的那样,如果成功的诊断代码与带有 2 个以上错误的失败的诊断代码不同,那就太好了。
  • 知道了。谢谢。我会继续并将其标记为答案,并与 TS 团队核对,以获得与众不同的东西。
猜你喜欢
  • 2022-08-15
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 2013-07-18
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 2010-12-14
相关资源
最近更新 更多