Files
template-MP/common/utils/env.js
2025-11-05 16:20:06 +08:00

80 lines
2.4 KiB
JavaScript
Raw Permalink 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.

/**
* 环境变量验证工具
*/
/**
* 验证必需的环境变量
* @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