我正在尝试在 angular 项目的网络 worker 中使用 tensorflow/tfjs (TF)。
使用 ng generate worker
创建网络 worker 命令工作得很好。
在组件中导入 TF 也很好。
但是,在工作人员中导入 TF,即:
import * as tf from '@tensorflow/tfjs'
通过 ng build
构建时会生成一堆缺少定义的错误命令。缺少的类型通常是与 DOM 相关的类型,例如 error TS2304: Cannot find name ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement
.这些类型在 TF 的某些定义中使用,据我所知,网络 worker 无法访问这些类型,因为 DOM manipulation cannot be done from workers .
我对此非常满意,我对 TF 的使用不依赖于这些类型。但是我仍然需要找到一种方法来构建我的 worker 。
因此,我试图修补
tsconfig.worker.json
文件。我的第一次尝试是通过在 compilerOptions.lib
中添加“dom”来模仿其他 tsconfig* 文件。大批 :["es2018", "webworker"]
取而代之["es2018", "webworker", "dom"]
这会导致类型定义冲突error TS6200: Definitions of the following identifiers conflict with those in another file
网络 worker 和 dom libs 对相同类型有不同的定义,但我当然不能删除 webworker lib 引用。我的第二次尝试是添加
skipTypeCheck
tsconfig.worker.json
中的编译器选项文件 :效果很好 ,我让 TF 在我的网络 worker 中运行并输出结果。
但...
跳过类型检查感觉就像是在破坏使用 typescript 的整个想法。所以我的问题是:
在保留类型检查的同时,是否有更简洁的方法在 angular 的 webworker 中使用 TF?
感谢您的回答。如果我应该提供更多配置细节,请告诉我。
最佳答案
来自官方 TensorFlow 教程:https://www.tensorflow.org/js/tutorials/setup
When using TypeScript you may need to set skipLibCheck: true in your tsconfig.json file if your project makes use of strict null checking or you will run into errors during compilation.
这比
skipTypeCheck
要好因为您的代码中的类型仍在检查中。这样代码就编译好了,但你仍然在控制台中得到一个错误:Error when getting WebGL context: Error: Cannot create a canvas in this context
.但到目前为止,这不是问题。
关于在 Web Worker 中导入 tensorflow 时出现 Angular typescript 类型检查问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64606267/