Files
rn-app/utils/config.ts
2025-11-07 13:50:18 +07:00

134 lines
3.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 应用配置工具
* 统一管理环境变量和配置
*/
import Constants from 'expo-constants';
import { Platform } from 'react-native';
/**
* 环境类型
*/
export type Environment = 'development' | 'staging' | 'production';
/**
* 获取当前环境
*/
export const getEnvironment = (): Environment => {
if (__DEV__) {
return 'development';
}
// 可以通过环境变量或其他方式判断 staging 环境
const env = process.env.EXPO_PUBLIC_ENV;
if (env === 'staging') {
return 'staging';
}
return 'production';
};
/**
* 获取 API 基础 URL
*/
export const getApiBaseUrl = (): string => {
// 1. 优先使用环境变量
const envApiUrl = process.env.EXPO_PUBLIC_API_URL;
if (envApiUrl) {
return envApiUrl;
}
// 2. 根据环境返回不同的 URL
const env = getEnvironment();
switch (env) {
case 'development':
// 开发环境
if (Platform.OS === 'web') {
// Web 平台使用代理服务器
// 代理服务器运行在 http://localhost:8086
// 会将 /api/* 请求转发到目标服务器
return 'http://localhost:8086/api';
} else {
// iOS/Android 使用本机 IP
// ⚠️ 重要:需要替换为你的本机 IP 地址
// 查看本机 IP
// - Windows: ipconfig
// - Mac/Linux: ifconfig
// - 或者使用 Metro Bundler 显示的 IP
// process.env.APP_IP_ADDRESS 在 .env.development.local 中配置 自己本地创建,避免提交到代码库
return process.env.APP_IP_ADDRESS || 'http://192.168.1.100:8086/api';
}
case 'staging':
// 预发布环境
return 'https://staging-api.yourdomain.com/api';
case 'production':
// 生产环境
return 'https://api.yourdomain.com/api';
default:
return '/api';
}
};
/**
* 获取 API 超时时间
*/
export const getApiTimeout = (): number => {
const timeout = process.env.EXPO_PUBLIC_API_TIMEOUT;
return timeout ? Number(timeout) : 10000;
};
/**
* 应用配置
*/
export const config = {
// 环境
env: getEnvironment(),
isDev: __DEV__,
// API 配置
api: {
baseURL: getApiBaseUrl(),
timeout: getApiTimeout(),
},
// 应用信息
app: {
name: process.env.EXPO_PUBLIC_APP_NAME || 'RN Demo',
version: process.env.EXPO_PUBLIC_APP_VERSION || '1.0.0',
bundleId: Constants.expoConfig?.ios?.bundleIdentifier || '',
packageName: Constants.expoConfig?.android?.package || '',
vk: 'fT6phq0wkOPRlAoyToidAnkogUV7ttGo',
nc: 1,
aseqId: '7',
},
// 平台信息
platform: {
os: Platform.OS,
version: Platform.Version,
isWeb: Platform.OS === 'web',
isIOS: Platform.OS === 'ios',
isAndroid: Platform.OS === 'android',
},
};
/**
* 打印配置信息(仅开发环境)
*/
export const printConfig = () => {
if (__DEV__) {
console.log('📋 App Configuration:', {
environment: config.env,
apiBaseURL: config.api.baseURL,
platform: config.platform.os,
version: config.app.version,
});
}
};
export default config;