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

react-native-dotenv在EAS构建中无法正常工作,求可行解决方案

EAS构建替代dotenv的可行解决方案
  • 使用EAS原生环境变量管理
    EAS构建本身集成了环境变量管理能力,完全可以替代dotenv的功能:

    1. 在项目根目录创建eas.json,为不同构建环境配置专属变量:
      {
        "build": {
          "development": {
            "env": {
              "API_URL": "https://dev.example.com",
              "DEBUG_MODE": "true"
            }
          },
          "production": {
            "env": {
              "API_URL": "https://prod.example.com",
              "DEBUG_MODE": "false"
            }
          }
        }
      }
      
    2. 临时测试时可以通过命令行直接传递变量:eas build --profile development --env API_URL=https://temp-dev.example.com
    3. 敏感密钥别明文写在配置里,用EAS Secrets存储:eas secret:create --name API_KEY --value your-secret-key --scope project,构建时会自动注入到环境中。
  • 用Babel插件嵌入环境变量
    习惯了process.env写法的话,可以通过Babel插件把变量直接编译进代码:

    1. 安装依赖:npm install babel-plugin-transform-inline-environment-variables --save-dev
    2. 修改babel.config.js,添加插件并指定要注入的变量:
      module.exports = function(api) {
        api.cache(true);
        return {
          presets: ['babel-preset-expo'],
          plugins: [
            ['transform-inline-environment-variables', {
              include: ['API_URL', 'API_KEY', 'DEBUG_MODE']
            }]
          ]
        };
      };
      
    3. 代码里直接用process.env.API_URL,EAS构建时会把对应环境变量替换成实际值。
  • 自定义脚本生成环境变量文件
    如果需要兼容原有的.env文件结构,可以写脚本在构建前把变量注入到代码文件:

    1. 编写scripts/generate-env.js:
      const fs = require('fs');
      const dotenv = require('dotenv');
      // 读取EAS当前构建的profile,默认用development
      const buildProfile = process.env.EAS_BUILD_PROFILE || 'development';
      // 加载对应环境的.env文件
      const envConfig = dotenv.config({ path: `.env.${buildProfile}` }).parsed || {};
      
      // 生成可导入的JS文件
      const outputContent = `export const ENV = ${JSON.stringify(envConfig)};`;
      fs.writeFileSync('./src/env.js', outputContent);
      
    2. 在package.json的scripts中添加前置脚本:"prebuild": "node scripts/generate-env.js"
    3. 构建时EAS会自动执行prebuild脚本,之后在代码里通过import { ENV } from './src/env'使用变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:01:31