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

运行React Native项目报错路径在项目或node_modules未找到如何解决

问题原因

你使用的普通dotenv库仅适用于Node.js运行环境,React Native运行在移动端JS上下文,没有原生的Node文件系统API,无法直接读取项目根目录的.env文件,所以会触发路径找不到的报错。

解决步骤
  • 卸载原来安装的普通dotenv:
npm uninstall dotenv
# 用yarn的话执行 yarn remove dotenv
  • 安装React Native专用的环境变量库react-native-dotenv,适配你用的0.66版本RN:
npm install react-native-dotenv@3.4.2 --save-dev
  • 打开项目根目录的babel.config.js文件,加入插件配置:
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    ["module:react-native-dotenv", {
      "moduleName": "@env",
      "path": ".env",
      "safe": false,
      "allowUndefined": true
    }]
  ]
};
  • 修改app.js代码,删除原有dotenv引入逻辑,直接从配置好的@env模块导入变量:
import { API_LOGIN } from '@env';

class UserLogin extends Component{
   //some code here
   apiCallHere=()=>{
      const url=API_LOGIN;
      fetch(url,{
         method: 'POST',  
         body: JSON.stringify({   
            email: email,
            password: password
         }),
         headers: new Headers({
            'Content-Type': 'application/json',
         })
      }).then(res => res.json())
      .catch(error => console.error('Error: ', error))
            
      .then((response) => {
         if (response.access_token != undefined) {
            this.setState({
               accessToken : response.access_token,
            });
            if(this.state.accessToken != ''){
               this.props.navigation.navigate('UserHomePage');
            }
         }
         else{
            alert('Unauthorised User');
         }
      })
   }
}
  • 清空缓存重启项目:
npx react-native start --reset-cache

重启后重新执行打包运行命令即可正常读取环境变量。

注意事项
  • 确保.env文件放在项目根目录,和package.json文件同级
  • 每次修改.env文件内容后都需要重启打包服务生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:15:04