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

Expo+React Native中react-native-dotenv报错:api.addExternalDependency不是函数

解决方案:

方案一:修复react-native-dotenv兼容性问题

报错api.addExternalDependency is not a function是因为你安装的react-native-dotenv版本过高,与当前Expo 47.x使用的Babel插件API不兼容。按以下步骤处理:

  1. 卸载当前版本的react-native-dotenv
npm uninstall react-native-dotenv
# 或 yarn remove react-native-dotenv
  1. 安装兼容的旧版本(v3.3.1经测试适配Expo 47)
npm install react-native-dotenv@3.3.1 --save-dev
# 或 yarn add react-native-dotenv@3.3.1 --dev
  1. 修改babel.config.js配置(注意参数名是blacklist/whitelist,而非新版本的blocklist/allowlist)
module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
    plugins: [
      ['module:react-native-dotenv', {
        moduleName: '@env',
        path: '.env',
        blacklist: null,
        whitelist: null,
        safe: false,
        allowUndefined: true
      }]
    ]
  };
};
  1. 解决VS Code无提示问题
    在项目根目录创建types/env.d.ts文件:
declare module '@env' {
  export const API_KEY: string;
}
  • TypeScript项目:在tsconfig.json中添加
{
  "compilerOptions": {
    "typeRoots": ["./types"]
  }
}
  • JavaScript项目:创建jsconfig.json并添加上述配置。

方案二:改用Expo官方环境变量方案(更简洁)

Expo自带环境变量支持,无需额外安装Babel插件:

  1. 在.env文件中定义变量,前缀必须为EXPO_PUBLIC_:
EXPO_PUBLIC_API_KEY='12345'
  1. 在代码中直接读取:
// 方式1:通过process.env
const apiKey = process.env.EXPO_PUBLIC_API_KEY;

// 方式2:通过expo-constants
import Constants from 'expo-constants';
const apiKey = Constants.expoConfig?.extra?.EXPO_PUBLIC_API_KEY;

这种方式无需配置Babel,VS Code会自动识别process.env的提示,且完全适配当前Expo版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:15:34