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

React Native(TypeScript+RN CLI)获取.env变量遇配置问题求助

React Native CLI + TypeScript 环境变量配置问题

项目依赖版本

{
  "@types/jest": "^28.1.4",
  "@types/react": "~17.0.21",
  "@types/react-native": "0.68.0",
  "@types/react-test-renderer": "^18.0.0",
  "babel-plugin-module-resolver": "^4.1.0",
  "react": "17.0.2",
  "react-native": "0.68.2",
  "react-native-config": "^1.4.12",
  "typescript": "^4.5.2",
  "react-native-dotenv": "3.4.7",
  "@types/react-native-dotenv": "0.2.0"
}

需求与已完成配置

需要在项目中读取.env文件的环境变量,已按官方文档及TypeScript相关步骤配置:

  • 创建.babelrc文件并配置react-native-dotenv插件
  • 插件配置中添加envName、moduleName、path项
  • .env文件格式为API_EXAMPLE=123
  • 创建types文件夹及env.d.ts文件,声明模块'@env'
  • 在tsconfig.json中添加typeRoots(此步骤导致单元测试报错,暂未解决)

已尝试的解决方案

  • 将导入的@env替换为react-native-dotenv
  • 执行yarn start --reset-cache重置缓存
  • 移动.env文件至根目录或types文件夹,重启IDE并重置缓存
  • 尝试.babelrc与babel.config.js的不同预设配置
  • 删除node_modules后重新安装依赖

报错信息

unable to resolve module '@env' from 'src/../.../../../MyFile.js: @env could not be found within the project
Error: Unable to resolve module path from node_modules/react-native-dotenv
Module ../.../node_modules_@types/react-native-dotenv has no exported member API_EXAMPLE

项目结构

projectFolder
--.github
--docs
--myApp(包含iOS、Android文件夹及组件运行所需文件)
--src
  |--- client
      |--- config
            |--- myApiConfigs.ts // 需在此获取.env变量(.env已加入.gitignore)
  |--- components // 所有React Native组件
-- .env // 位于根目录,也曾尝试放在types文件夹

请问是否遗漏了某些配置步骤?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:45:38