You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native TypeScript配置路径别名报Cannot find module错误怎么解决?

问题根因及修复方案

1. 修复tsconfig.json配置

你当前的include字段仅包含了src目录下的文件,但入口App.tsx位于项目根目录,TS不会对src外的文件做路径别名解析,这是触发TS(2307)报错的核心原因。修改tsconfig.json的include字段:

{
  "extends": "expo/tsconfig.base",
  // 调整include覆盖所有项目文件,或显式添加根目录文件
  "include": ["./**/*"],
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react-native",
    "lib": ["es2017"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext",
    "baseUrl": ".",
    "paths": {
      "@util/*": ["./src/util/*"],
      "@components/*": ["./src/components/*"]
    }
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}

同时移除paths配置最后一项的尾逗号,避免低版本TS解析异常。

2. 安装缺失的eslint依赖

你在eslint中配置了TS和Babel路径解析规则,但未安装对应的解析器依赖,执行命令安装:

yarn add -D eslint-import-resolver-typescript eslint-import-resolver-babel-module

3. 启用eslint的babel-module解析器

修改.eslintrc.js的settings字段,取消babel-module的注释:

settings: {
  'import/resolver': {
    node: {
      path: ['src'],
      extensions: ['.js', '.jsx', '.ts', '.tsx'],
    },
    typescript: {
      alwaysTryTypes: true,
    },
    'babel-module': {}, // 移除注释启用
  },
}

4. 清除缓存重启服务

  • 运行npx expo start --clear清除Metro打包缓存
  • VSCode中按Ctrl/Command + Shift + P,选择「TypeScript: Restart TS Server」重启TS语言服务

内容的提问来源于stack exchange,提问作者ProvingBard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 04:36:08