You've already forked template-MP
新增:全量优化
This commit is contained in:
80
common/utils/env.js
Normal file
80
common/utils/env.js
Normal file
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* 环境变量验证工具
|
||||
*/
|
||||
/**
|
||||
* 验证必需的环境变量
|
||||
* @param {Array<string>} requiredVars 必需的环境变量键名数组
|
||||
* @throws {Error} 如果有任何必需的环境变量缺失则抛出错误
|
||||
*/
|
||||
export function validateEnv(requiredVars = []) {
|
||||
const missingVars = []
|
||||
for (const key of requiredVars) {
|
||||
if (!import.meta.env[key]) {
|
||||
missingVars.push(key)
|
||||
}
|
||||
}
|
||||
if (missingVars.length > 0) {
|
||||
throw new Error(`缺少必需的环境变量: ${missingVars.join(', ')}`)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 获取环境变量,带默认值和类型转换
|
||||
* @param {string} key 环境变量键名
|
||||
* @param {any} defaultValue 默认值
|
||||
* @param {string} type 类型 ('string' | 'number' | 'boolean' | 'array')
|
||||
* @returns {any} 环境变量值
|
||||
*/
|
||||
export function getEnv(key, defaultValue = null, type = 'string') {
|
||||
const value = import.meta.env[key]
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return defaultValue
|
||||
}
|
||||
switch (type) {
|
||||
case 'number':
|
||||
const numValue = Number(value)
|
||||
return isNaN(numValue) ? defaultValue : numValue
|
||||
case 'boolean':
|
||||
return value === 'true' || value === '1'
|
||||
case 'array':
|
||||
try {
|
||||
return JSON.parse(value)
|
||||
} catch (e) {
|
||||
return Array.isArray(defaultValue) ? defaultValue : []
|
||||
}
|
||||
case 'string':
|
||||
default:
|
||||
return value
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 环境变量配置
|
||||
*/
|
||||
export const EnvConfig = {
|
||||
// API基础URL
|
||||
BASE_URL: getEnv('VITE_BASE_URL', '', 'string'),
|
||||
// 静态资源URL
|
||||
ASSETS_URL: getEnv('VITE_ASSETSURL', '', 'string'),
|
||||
// 小程序APPID
|
||||
APP_ID: getEnv('VITE_APPID', '', 'string'),
|
||||
// UNI-APPID
|
||||
UNI_APP_ID: getEnv('VITE_UNI_APPID', '', 'string'),
|
||||
// 是否为开发环境
|
||||
IS_DEV: getEnv('NODE_ENV', 'development', 'string') === 'development',
|
||||
// 是否为生产环境
|
||||
IS_PROD: getEnv('NODE_ENV', 'development', 'string') === 'production',
|
||||
// 调试模式
|
||||
DEBUG: getEnv('VITE_DEBUG', false, 'boolean'),
|
||||
// API超时时间(毫秒)
|
||||
API_TIMEOUT: getEnv('VITE_API_TIMEOUT', 10000, 'number'),
|
||||
}
|
||||
// 验证必需的环境变量
|
||||
try {
|
||||
validateEnv(['VITE_BASE_URL', 'VITE_APPID'])
|
||||
} catch (error) {
|
||||
console.error('环境变量验证失败:', error.message)
|
||||
// 在开发环境中抛出错误
|
||||
if (EnvConfig.IS_DEV) {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
export default EnvConfig
|
||||
Reference in New Issue
Block a user