ES6动态导入类报错:TestCommand不是构造函数的解决咨询
解决动态导入ES模块默认导出类的构造函数错误
我一眼就看出问题啦——你用await import()拿到的是整个模块对象,而不是直接的默认导出类!静态导入的时候import TestCommand from "...";会自动帮你提取默认导出,但动态导入需要你手动去取.default属性。
修正后的代码
直接修改你动态导入的部分,加上.default就能拿到真正的类构造函数了:
async function loadCommand(command) { // 提取模块的默认导出 const { default: TestCommand } = await import("./commands/TestCommand.js"); const test = new TestCommand(); console.log(test.getName()); // 现在能正常输出"Test"啦 }
或者你也可以这样写,效果完全一致:
async function loadCommand(command) { const module = await import("./commands/TestCommand.js"); const TestCommand = module.default; const test = new TestCommand(); console.log(test.getName()); }
为什么静态导入没问题?
静态的import TestCommand from "...";是ES模块的语法糖,它本质上就是从模块对象中提取default属性并赋值给TestCommand变量;而动态导入import()则会返回一个包含所有导出(包括默认导出和命名导出)的Promise,所以你得自己手动获取默认导出。
额外小提醒
如果你的模块有命名导出,动态导入的时候也可以用解构直接获取,比如给TestCommand.js加个命名导出的工具函数:
// TestCommand.js里添加命名导出 export const helperFn = () => console.log("我是工具函数"); // 动态导入时同时获取默认和命名导出 async function loadCommand(command) { const { default: TestCommand, helperFn } = await import("./commands/TestCommand.js"); const test = new TestCommand(); helperFn(); // 调用命名导出的函数 }
内容的提问来源于stack exchange,提问作者user12346820
相关产品推荐
相关产品推荐

