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

非Expo React Native项目react-native-dotenv路径找不到求助

解决非Expo React Native项目中react-native-dotenv的path模块找不到问题

问题分析

错误提示无法解析path模块,本质是React Native的Metro打包器默认不支持Node.js核心模块(如path、fs),而react-native-dotenv在非Expo环境下依赖这些模块读取.env文件,同时版本不兼容也会加剧该问题。

解决步骤

1. 安装兼容版本的react-native-dotenv

卸载当前版本,安装适配非Expo项目的稳定版本:

npm uninstall react-native-dotenv
npm install react-native-dotenv@3.4.9 --save-dev

2. 配置Metro支持Node核心模块

在项目根目录新建或修改metro.config.js,添加核心模块的兼容实现:

const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');

module.exports = mergeConfig(getDefaultConfig(__dirname), {
  resolver: {
    extraNodeModules: {
      path: require.resolve('path-browserify'),
      fs: require.resolve('react-native-level-fs'),
    },
  },
});

3. 安装对应的依赖包

安装上述配置中用到的兼容模块:

npm install path-browserify react-native-level-fs --save

4. 确认Babel配置正确性

保持你的babel.config.js配置不变,确保使用@env作为导入模块名:

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'module:react-native-dotenv',
      {
        envName: 'APP_ENV',
        moduleName: '@env',
        path: '.env',
      },
    ],
  ],
};

5. 清理缓存并重启Metro

执行命令清除缓存,避免旧配置干扰:

npx react-native start --reset-cache

使用方式

在代码中正确导入环境变量:

import { YOUR_ENV_VAR } from '@env';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:50:39