React Native 如何向app.json文件添加环境变量

ttvkxqim  于 2022-11-25  发布在  React
关注(0)|答案(1)|浏览(174)

我的Expo项目中有一个app.json文件,在这个文件中有两个API键(下面标记为API_KEY),我想通过环境变量隐藏它们。
如何使用环境变量而不是硬编码API密钥?

应用程序.json

{
  "expo": {
    "name": "Closeout",
    "slug": "Closeout",
    "version": "1.0.0",
    "orientation": "portrait",
    "privacy": "hidden",
    "notification": {
      "icon": "./assets/images/notification-icon.png",
      "color": "#000000",
      "iosDisplayInForeground": true
    },
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": ["**/*"],
    "ios": {
      "icon": "./assets/images/icon.png",
      "buildNumber": "2",
      "config": {
        "googleMapsApiKey": "API_KEY"
      }
    },
    "android": {
      "adaptiveIcon": {
        "foregroundImage": "./assets/images/icon.png",
        "backgroundColor": "#000"
      },
      "versionCode": 5,
      "useNextNotificationsApi": true,
      "config": {
        "googleMaps": {
          "apiKey": "API_KEY"
        }
      },
      "googleServicesFile": "./google-services.json"
    }
  }
}
ulydmbyx

ulydmbyx1#

我猜你现在可能已经找到了一个解决方案或者尝试了其他的方法。但是,这里有一个解决这个问题的方法,我希望它能帮助任何面临同样挑战的人。这是我正在实现的一个打字脚本环境。
创建覆盖app.json文件内容的app.config.ts文件

import { ExpoConfig, ConfigContext } from '@expo/config';
import * as dotenv from 'dotenv';

// initialize dotenv
dotenv.config();

export default ({ config }: ConfigContext): ExpoConfig => ({
  ...config,
  slug: 'my-app',
  name: 'My App',
  ios: {
    supportsTablet: true,
    bundleIdentifier: 'com.croon',
    config: {
      googleMapsApiKey: process.env.GOOGLE_CLOUD_API_KEY,
    },
  },
  android: {
    adaptiveIcon: {
      foregroundImage: './assets/adaptive-icon.png',
      backgroundColor: '#FFFFFF',
    },
    package: 'com.croon',
    config: {
      googleMaps: {
        apiKey: process.env.GOOGLE_CLOUD_API_KEY,
      },
    },
  },
});

然后,您可以在app.json文件中将API条目保留为空。

{
  "expo": {
    "name": "Closeout",
    "slug": "Closeout",
    "version": "1.0.0",
    "orientation": "portrait",
    "privacy": "hidden",
    "notification": {
      "icon": "./assets/images/notification-icon.png",
      "color": "#000000",
      "iosDisplayInForeground": true
    },
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": ["**/*"],
    "ios": {
      "icon": "./assets/images/icon.png",
      "buildNumber": "2",
      "config": {
        "googleMapsApiKey": ""
      }
    },
    "android": {
      "adaptiveIcon": {
        "foregroundImage": "./assets/images/icon.png",
        "backgroundColor": "#000"
      },
      "versionCode": 5,
      "useNextNotificationsApi": true,
      "config": {
        "googleMaps": {
          "apiKey": ""
        }
      },
      "googleServicesFile": "./google-services.json"
    }
  }
}

请记住安装所需的依赖项
干杯!干杯!

相关问题