TypeScript跨同级目录导入模块提示找不到模块
TypeScript跨目录模块导入错误修复
问题场景
项目结构如下:
- src - tsconfig.json - types - math.types.ts - utils - addNumbers.ts - playwright - tsconfig.json - dashboard.page.ts
src目录的React应用和工具类本地编译正常,但在playwright目录执行tsc -p tsconfig.json时,出现以下错误:
../src/utils/addNumbers.ts:4:45 - error TS2307: Cannot find module 'types/math.types' or its corresponding type declarations. import { SomeNumberType } from 'types/math.types';
问题原因
src目录的tsconfig应该配置了路径映射,让types/xxx这类导入能被正确解析,但playwright目录的tsconfig缺少对应的路径配置,导致TypeScript无法识别addNumbers.ts中导入的types/math.types模块。
解决方案
修改playwright目录下的tsconfig.json,在compilerOptions中添加src目录的路径映射,并补充include字段确保src文件被纳入类型检查:
{ "compilerOptions": { "strict": true, "target": "es2017", "module": "commonjs", "skipLibCheck": true, "moduleResolution": "node", "baseUrl": ".", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "paths": { "*": ["*", "tests/*"], "types/*": ["../src/types/*"], "utils/*": ["../src/utils/*"] }, "noEmit": true }, "include": ["../src/**/*", "./**/*"] }
配置说明
paths字段新增"types/*": ["../src/types/*"]和"utils/*": ["../src/utils/*"],让TypeScript解析对应模块时自动指向src目录下的目标文件include字段包含../src/**/*,确保src目录下所有TypeScript文件都被TypeScript识别,避免其他潜在的导入错误
内容的提问来源于stack exchange,提问作者Knight
相关产品推荐
相关产品推荐

