ts-mocha 结合 node-fetch 测试报错:未知文件扩展名.ts
解决ts-mocha + node-fetch 出现的 ".ts" 文件扩展名未知错误
核心原因
这个错误本质是模块解析规则冲突:node-fetch v3+是纯ES模块,而ts-mocha默认可能以CommonJS模式运行,当两种模块模式混合时,Node.js的模块解析器无法正确识别.ts文件的扩展名(ES模块模式下Node不自动处理.ts,需要由ts-mocha的编译流程接管)。另外测试代码里的冗余动态导入也可能加剧这个问题。
分步解决方案
1. 处理node-fetch版本冲突
如果你的项目是CommonJS配置(默认),直接降级到兼容CommonJS的node-fetch v2:
npm install node-fetch@2
如果坚持用v3+,需要把项目切换为ES模块模式:在package.json中添加"type": "module",同时调整tsconfig的module为ESNext。
2. 修正tsconfig.json配置
确保TypeScript编译输出符合运行环境的模块规范:
{ "compilerOptions": { "module": "CommonJS", // 对应node-fetch v2;用v3则改为ESNext "target": "ES2017", "esModuleInterop": true, // 解决CommonJS和ES模块的导入兼容问题 "moduleResolution": "node" }, "include": ["src/**/*", "test/**/*"] }
3. 清理测试代码中的冗余逻辑
测试文件里的before钩子重复动态导入useFetch完全没必要,直接删除该钩子,修改后的测试代码:
import { expect } from 'chai'; import useFetch from './useFetch'; describe("useFetch", function() { describe("get", () => { it("test", async () => { const result = await useFetch(); // 注意:fetch返回的是Response对象,不是字符串,原断言会失败,建议改为断言响应状态 expect(result.ok).to.be.true; }); }); });
4. 确保ts-mocha运行命令正确
运行测试时指定tsconfig,确保编译流程正常:
- CommonJS模式:
ts-mocha -p tsconfig.json test/**/*.ts
- ES模块模式(package.json加了"type": "module"):
ts-mocha --esm -p tsconfig.json test/**/*.ts
内容的提问来源于stack exchange,提问作者Maarten Raaijmakers
相关产品推荐
相关产品推荐

