Handling different environments

根據環境(pro、stage、dev...)而配置環境參數

使用 React-Native-Config 此Library

設定步驟參考 Setup部分

使用的方式 參考 Usage部分(下方只貼上RN內的使用方式)

RN

在RN專案下創建新檔案 .env

API_URL=https://myapi.com
GOOGLE_MAPS_API_KEY=abcdefgh

獲取定義的參數

import Config from 'react-native-config'

Config.API_URL  // 'https://myapi.com'
Config.GOOGLE_MAPS_API_KEY  // 'abcdefgh'

Keep in mind this module doesn't obfuscate or encrypt secrets for packaging, so do not store sensitive keys in .env. It's basically impossible to prevent users from reverse engineering mobile app secrets, so design your app (and APIs) with that in mind.

執行(下方只貼上RN內的使用方式)

將不同的環境變數設定寫在各個檔案內: .env.stage 、 .env.dev

react-native-config 預設是讀取 .env ,但當在build或者release app時可以更改

$ ENVFILE=.env.staging react-native run-ios           # bash
$ SET ENVFILE='.env.staging' && react-native run-ios  # windows
$ env:ENVFILE=".env.staging"; react-native run-ios    # powershell

參考

Last updated