如何正确导入使用module.exports = { default: ... }导出的模块?
问题分析与解决
你的问题核心在于模块导出结构和TypeScript类型系统的不匹配,以及对esModuleInterop作用的理解偏差:
为什么默认导入会报错?
该模块的CommonJS导出是一个包含default属性的对象,而非直接导出函数(标准CommonJS默认导出是module.exports = preprocessor)。当开启esModuleInterop: true时,TypeScript会自动将标准CommonJS模块的module.exports映射为ES模块的默认导出,但这个模块的导出结构不符合这个标准——TS的类型系统会误以为import cucumber from '...'拿到的是preprocessor函数,但实际运行时你拿到的是包含default属性的导出对象,所以调用时会触发default is not a function的错误。
更优的解决办法
方法1:明确命名导入取default
用ES6命名导入语法直接获取default属性,既能符合ES模块规范,又能通过TypeScript类型检查:
import { default as cucumber } from 'cypress-cucumber-preprocessor';
方法2:修正模块类型定义(如果类型文件不准确)
如果@types/cypress-cucumber-preprocessor的类型定义和实际模块导出不符,你可以在项目中添加自定义类型声明文件(比如cypress-cucumber-preprocessor.d.ts):
declare module 'cypress-cucumber-preprocessor' { export type Preprocessor = (options?: Record<string, any>) => (file: Record<string, any>) => Promise<string>; export const default: Preprocessor; export function transform(filePath: string, fileContent: string): string; }
这样TypeScript就能正确识别模块的导出结构,避免类型检查错误。
为什么之前的方案有问题?
- 方案1中TS报错,是因为类型定义错误地将模块默认导出标记为函数,而实际导出是包含
default属性的对象,类型系统和运行时行为不一致。 - 方案2用
require虽然能运行,但违背了你想用ES6导入的初衷,还需要手动添加类型断言,不够优雅。
内容的提问来源于stack exchange,提问作者Alexey Romanov
相关产品推荐
相关产品推荐

