如何在TypeScript中正确导入CommonJS模块导出的类定义?
解决方案:TypeScript中正确导入默认导出的CommonJS模块
问题根源
AsyncAPI Generator是CommonJS模块,它通过module.exports = Generator直接导出类本身(属于默认导出),但你用了TypeScript的具名导入语法,导致编译后代码尝试从require()返回的对象中取Generator属性,而实际上这个对象就是类本身,因此触发TypeError: generator_1.Generator is not a constructor错误。
方法1:调整TypeScript导入语法
改用默认导入语法替代具名导入:
import Generator from '@asyncapi/generator'; const generator = new Generator('@asyncapi/html-template', './test');
编译后会生成与纯JS示例一致的正确代码:
const Generator = require("@asyncapi/generator"); const generator = new Generator('@asyncapi/html-template', './test');
方法2:修正自定义类型声明
你的类型声明目前是按具名导出定义的,需要改成默认导出形式:
declare module '@asyncapi/generator' { class Generator { constructor(templateName: string, targetDir: string, options?: any); // 补充你需要的其他方法定义 } export default Generator; }
修改后TypeScript就能识别该模块的默认导出类型,配合方法1的导入语法即可正常工作。
额外提示:优化tsconfig配置
如果项目同时兼容ES模块和CommonJS模块,建议在tsconfig.json中添加以下配置,提升模块兼容性:
{ "compilerOptions": { "module": "CommonJS", // 根据项目运行环境调整,Node.js环境推荐用CommonJS "esModuleInterop": true, // 自动处理CommonJS模块的默认导入逻辑 "allowSyntheticDefaultImports": true } }
esModuleInterop选项能让TypeScript更友好地适配CommonJS模块的导出规则,减少手动调整导入语法的麻烦。
内容的提问来源于stack exchange,提问作者Jiri
相关产品推荐
相关产品推荐

