如何正确实例化VoximplantApiClient?ES6导入报错求助
正确实例化VoximplantApiClient的ES6导入方案
这个问题的核心是@voximplant/apiclient-nodejs属于CommonJS模块,Node.js处理它的ES6导入时,不会自动映射命名导出,得用下面的方式处理:
正确的ES6导入+实例化代码
import pkg from '@voximplant/apiclient-nodejs'; const { VoximplantApiClient } = pkg; // 实例化客户端(记得传入你的认证信息) const client = new VoximplantApiClient({ credentials: { username: '你的Voximplant账号', password: '你的Voximplant密码' } });
为什么之前的导入方式会报错?
- 直接用
import VoximplantApiClient from '@voximplant/apiclient-nodejs'时,你导入的是整个模块对象,而非构造函数本身,所以执行new VoximplantApiClient()会提示“不是构造函数”。 - 用命名导入
import { VoximplantApiClient } from...报错,是因为CommonJS模块没有ES6标准的命名导出,Node.js会把module.exports作为模块的默认导出,因此必须从默认导出里解构出构造函数。
完整API调用示例(以添加用户为例)
import pkg from '@voximplant/apiclient-nodejs'; const { VoximplantApiClient } = pkg; const client = new VoximplantApiClient({ credentials: { username: '你的账号', password: '你的密码' } }); async function addUser() { try { const response = await client.Users.addUser({ userName: 'demo_user', userDisplayName: 'Demo User', userPassword: 'DemoPass123' }); console.log('用户创建成功:', response); } catch (err) { console.error('创建失败:', err); } } addUser();
内容的提问来源于stack exchange,提问作者type
相关产品推荐
相关产品推荐

