TypeScript路径别名需显式加/index才能解析的问题求助
问题描述
使用TypeScript路径别名时碰到以下问题:
- 直接写
import { Colors } from "@utils";或import { Colors } from "@utils/";会报错:Cannot find module '@utils' or its corresponding type declarations. - 但显式加上
/index(比如import { Colors } from "@utils/index";)就能正常导入 - 更奇怪的是,用
@utils/folder-example/..这种先进子文件夹再返回的方式,居然能自动识别目录下的index.ts,但直接用别名却不行,所有配置的路径别名都有这个问题
当前的tsconfig.json配置如下:
{ "extends": "expo/tsconfig.base", "compilerOptions": { "allowSyntheticDefaultImports": true, "module": "CommonJS", "moduleDetection": "force", "moduleResolution": "node", "strict": true, "baseUrl": "./", "paths": { "@utils/*": [ "./src/utils/*" ] } } }
我有两个疑问:
- 这是预期行为吗?
- 怎么配置才能让路径别名不用显式加
/index就能正常解析?
解决方案
关于第一个疑问
这不是预期行为,正常情况下TypeScript应该能自动把目录映射到它下面的index文件。问题出在你当前的paths配置规则上——现有的@utils/*只匹配带后缀的路径,不匹配@utils本身。
关于第二个疑问
调整tsconfig.json的paths配置,补充一条不带通配符的别名规则,同时保留原有带通配符的规则,这样既能支持直接导入目录(自动找index),也能支持导入目录下的子文件:
{ "extends": "expo/tsconfig.base", "compilerOptions": { "allowSyntheticDefaultImports": true, "module": "CommonJS", "moduleDetection": "force", "moduleResolution": "node", "strict": true, "baseUrl": "./", "paths": { "@utils": ["./src/utils"], "@utils/*": ["./src/utils/*"] } } }
也可以直接指定index文件,效果是一样的:
{ "extends": "expo/tsconfig.base", "compilerOptions": { "allowSyntheticDefaultImports": true, "module": "CommonJS", "moduleDetection": "force", "moduleResolution": "node", "strict": true, "baseUrl": "./", "paths": { "@utils": ["./src/utils/index"], "@utils/*": ["./src/utils/*"] } } }
额外注意(Expo项目)
如果调整后打包工具(Metro)还是识别不了,需要在metro.config.js里同步配置别名:
const { getDefaultConfig } = require('expo/metro-config'); const config = getDefaultConfig(__dirname); config.resolver.alias = { ...config.resolver.alias, '@utils': './src/utils', }; module.exports = config;
内容的提问来源于stack exchange,提问作者zaqijr7
相关产品推荐
相关产品推荐

