使用nodenext模块解析时ts-mocha与tsc导入路径后缀冲突求助
解决TypeScript+Mocha测试的导入后缀冲突问题
问题根源
开启moduleResolution: nodenext后,TypeScript要求相对导入必须带.js后缀(对应编译后的输出文件),但ts-mocha直接运行.test.ts文件时,会尝试寻找实际不存在的.js源文件,导致模块找不到;去掉后缀TS又会抛出格式错误。
可行解决方案
方案1:给测试文件单独配置tsconfig
新建tsconfig.test.json,继承主配置的同时调整测试相关编译选项,让TS和ts-mocha规则对齐:
{ "extends": "./tsconfig.json", "compilerOptions": { "moduleResolution": "node", "allowImportingTsExtensions": true, "noEmit": true }, "include": ["tests"] }
运行测试时指定这个配置文件:
ts-mocha -p tsconfig.test.json tests/*.test.ts
该方案无需提前编译源码,适合快速迭代测试。
方案2:编译源码后测试编译产物
先执行编译命令把源码转译到dist目录,测试文件里导入编译后的.js文件:
// 测试文件导入路径改为指向dist import x from '../dist/format.js'
把编译和测试命令整合到package.json脚本中:
{ "scripts": { "build": "tsc -p tsconfig.build.json", "test": "npm run build && ts-mocha tests/*.test.ts" } }
执行npm test即可完成编译+测试,该方案确保测试的是与生产环境一致的代码。
方案3:用ESM模式运行ts-mocha
若项目为纯ESM模式(package.json设置"type": "module"),可开启TS的allowImportingTsExtensions选项,测试文件直接导入.ts后缀的源码:
import x from '../lib/format.ts'
新建tsconfig.test.json:
{ "extends": "./tsconfig.json", "compilerOptions": { "allowImportingTsExtensions": true, "noEmit": true }, "include": ["tests"] }
运行测试时添加--esm参数:
ts-mocha --esm -p tsconfig.test.json tests/*.test.ts
内容的提问来源于stack exchange,提问作者Filippo Valsorda
相关产品推荐
相关产品推荐

