请按照以下步骤操作
-
Install 曝光常数包裹。要安装该软件包,请运行以下命令。
npm i 展览常数
-
Add 环境.js文件并粘贴以下代码。
import Constants from 'expo-constants';
import { Platform } from 'react-native';
const localhost = Platform.OS === 'ios' ? 'localhost:8080' : '10.0.2.2:8080';
const ENV = {
dev: {
apiUrl: 'https://dev.myapi.com/api',
amplitudeApiKey: null,
},
staging: {
apiUrl: 'https://uat.myapi.com/api',
amplitudeApiKey: '[Enter your key here]',
// Add other keys you want here
},
prod: {
apiUrl: 'https://prod.myapi.com/api',
amplitudeApiKey: '[Enter your key here]',
// Add other keys you want here
},
};
const getEnvVars = (env = Constants.manifest.releaseChannel) => {
// What is __DEV__ ?
// This variable is set to true when react-native is running in Dev mode.
// __DEV__ is true when run locally, but false when published.
if (__DEV__) {
return ENV.dev;
} else if (env === 'staging') {
return ENV.staging;
} else if (env === 'prod') {
return ENV.prod;
}
};
export default getEnvVars;
- 访问环境变量
// Import getEnvVars() from environment.js
import getEnvVars from '../environment';
const { apiUrl } = getEnvVars();
/******* SESSIONS::LOG IN *******/
// LOG IN
// credentials should be an object containing phone number:
// {
// "phone" : "9876342222"
// }
export const logIn = (credentials, jsonWebToken) =>
fetch(`${apiUrl}/phone`, {
method: 'POST',
headers: {
Authorization: 'Bearer ' + jsonWebToken,
'Content-Type': 'application/json',
},
body: JSON.stringify(credentials),
});
- 要创建构建,请使用以下命令。
开发 - 博览会构建:ios --release-channel dev
登台 - expo build:ios --release-channel 登台
生产 - expo build:ios --release-channel prod
现在 Expo 支持 app.config.js 或 app.config.ts 等配置文件,我们可以使用 dotenv。检查一下:https://docs.expo.io/guides/environment-variables/#using-a-dotenv-file https://docs.expo.io/guides/environment-variables/#using-a-dotenv-file
- 参考链接 https://alxmrtnz.com/thoughts/2019/03/12/environment-variables-and-workflow-in-expo.html