Typescript导入depthkit模块报错DepthKit不是构造函数如何修复
问题解决步骤
报错的核心原因是depthkit库的导出格式为UMD/CommonJS,未使用ES模块的命名导出规则,所以你之前的命名导入写法无法拿到构造函数。按以下步骤排查解决:
- 第一种:使用默认导入
先修改导入写法为默认导入:
该写法需要你在import DepthKit from 'depthkit/build/depthkit' const depthkit = new DepthKit()tsconfig.json的compilerOptions中开启以下配置:{ "esModuleInterop": true, "allowSyntheticDefaultImports": true } - 第二种:兼容CommonJS导出的导入写法
如果第一种写法仍然报错,说明构造函数挂载在模块的default属性上,用以下写法:import * as DK from 'depthkit/build/depthkit' const depthkit = new DK.default() - 第三种:简化路径+直接用CommonJS导入
先尝试去掉路径中的build层级直接从包根导入,同时用require写法适配:const DepthKit = require('depthkit') const depthkit = new DepthKit() - 验证导出结构
如果以上写法都无效,可以先打印导入的模块对象确认实际结构:
根据控制台输出的对象结构,找到构造函数的实际挂载位置即可。import * as DK from 'depthkit/build/depthkit' console.log('模块导出内容:', DK) - 类型声明补全
如果TS提示找不到模块的类型声明,可以在项目src目录下新建depthkit.d.ts文件,写入以下内容自定义类型:declare module 'depthkit' { export default class DepthKit { constructor(options?: any) // 可根据库的使用说明补充其他方法和属性的类型定义 } }
内容的提问来源于stack exchange,提问作者user15635022
相关产品推荐
相关产品推荐

