问题描述
我正在使用脚本标签加载可教机器图像库:
<script src="https://cdn.jsdelivr.net/npm/@teachablemachine/image@0.8/dist/teachablemachine-image.min.js"></script>
在我的打字稿项目中,我使用 tmImage
代码如下:
let model = await tmImage.load(modelURL,MetadataURL)
这在 Typescript 中给出了这个错误:
cannot find name `tmImage`
所以我需要类型声明文件,这些文件在 https://github.com/DefinitelyTyped/ 上不可用,但在实际模块中可用。所以我安装了它:
npm install @teachablemachine/image
现在,在 node_modules 中有很多交叉引用的 .d.ts
文件,其中包含所有需要的类型信息。
我假设 Visual Studio Code 会自动从我的项目中的 .d.ts
文件中获取所有信息,但这仅在我实际 import
模块时发生:
import * as tmImage from '@teachablemachine/image';
现在可以通过代码完成很好地识别类型,但我还需要编译可教机器代码和我自己的代码!
是否可以在开发期间仅使用来自 node_modules 的类型信息,或者我是否需要放弃我的 <script>
标签并自己编译所有 teachable machine
代码,仅仅因为我使用 Typescript?
解决方法
您不是每次都编译库,您只是导入它。该库已在 node_modules 内编译。因此,您可以使用导入并将它们从您的打包器中排除(如果您正在使用)。
如果您希望类型全局可用,您需要将 .d.ts
文件添加到您的项目中。 TS 不会仅仅因为它在 node_modules 上就假设一个类型可用,但您可以通过扩展全局命名空间来添加它,如下所示:
// In a `.d.ts` file within the included folders of your project
import * as _tmImage from '@teachablemachine/image';
declare global {
const tmImage: typeof _tmImage;
}