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

React Native项目设置tsconfig.json的typeRoots报错问题

React Native添加typeRoots后类型定义报错的解决办法

问题说明

在React Native项目的tsconfig.json的compilerOptions中添加typeRoots配置后,出现以下错误:

Cannot find type definition file for 'react-native'.
The file is in the program because:
Entry point of type library 'react-native' specified in compilerOptions

仅在添加typeRoots时触发该错误

项目依赖版本:

  • react-native: 0.74.2
  • @tsconfig/react-native: ^3.0.5

当前tsconfig.json配置如下:

{
  "extends": "@tsconfig/react-native/tsconfig.json",
  "include": [
    "./src/**/*"
  ],
  "exclude": [
    "**/node_modules/**",
    "./node_modules/@types/react-native",
    "babel.config.js",
    "metro.config.js",
    "jest.config.ts"
  ],
  "compilerOptions": {
    "outDir": "./dist",
    "typeRoots": [
      "node_modules/@types",
      "./type-definitions",
      "./theme.d.ts"
    ],
    "lib": [
      "esnext"
    ],
    "target": "ESNext",
    "module": "ESNext",
    "declaration": true,
    "declarationMap": true,
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "strict": true,
    "jsx": "react-native"
  }
}

错误原因

  1. typeRoots配置格式错误:typeRoots仅支持指定类型定义文件夹路径,直接将单个.d.ts文件./theme.d.ts加入其中,TypeScript会将其当作文件夹解析,导致路径异常。
  2. 自定义typeRoots覆盖默认逻辑:React Native 0.70+版本的类型定义内置在react-native包本身(路径为node_modules/react-native/types),自定义typeRoots后会覆盖TypeScript默认的类型查找规则,导致无法定位到RN的内置类型。
  3. 不必要的排除项干扰:配置中排除了./node_modules/@types/react-native,虽然RN 0.70+不再使用这个包,但该排除项可能影响类型查找逻辑。

解决步骤

1. 修正typeRoots的路径配置

将单个.d.ts文件从typeRoots中移除,放到include数组里:

{
  "include": [
    "./src/**/*",
    "./theme.d.ts"
  ],
  "compilerOptions": {
    "typeRoots": [
      "node_modules/@types",
      "./type-definitions"
    ],
    // 其他配置保持不变
  }
}

2. 让TypeScript找到RN的内置类型

有两种方式可以实现:

  • 方式一:在typeRoots中添加RN类型路径
    直接将RN内置类型的文件夹路径加入typeRoots:

    "compilerOptions": {
      "typeRoots": [
        "node_modules/@types",
        "./type-definitions",
        "node_modules/react-native/types"
      ]
    }
    
  • 方式二:用types字段显式指定RN类型
    在compilerOptions中添加types数组,明确声明要加载的类型库:

    "compilerOptions": {
      // 其他配置不变
      "types": ["react-native"]
    }
    

3. 移除多余的排除项

删除exclude数组中的./node_modules/@types/react-native:

"exclude": [
  "**/node_modules/**",
  "babel.config.js",
  "metro.config.js",
  "jest.config.ts"
]

4. 重新安装依赖(可选)

如果以上步骤后仍有问题,执行依赖重装:

npm install

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 13:32:04