From 887b43277b4fea9100e727038f5f2b099c2e433a Mon Sep 17 00:00:00 2001 From: terwer Date: Sun, 5 Mar 2023 22:59:32 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E7=8E=AF=E5=A2=83=E5=8F=98=E9=87=8F?= =?UTF-8?q?=E8=AF=BB=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/envUtil.ts | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/src/utils/envUtil.ts b/src/utils/envUtil.ts index 5562bd9e..0693089f 100644 --- a/src/utils/envUtil.ts +++ b/src/utils/envUtil.ts @@ -24,7 +24,7 @@ */ /** - * 获取环境变量 + * 获取环境变量,未定义返回空 * * @param key key * @author terwer @@ -33,16 +33,27 @@ const getEnv = (key: string): string => { let env = "" try { - if (import.meta.env[key]) { - env = import.meta.env[key] - } - } catch (e: any) { - throw new Error(e) - } - + env = import.meta.env[key] ?? "" + } catch (e: any) {} return env } +/** + * 获取环境变量,如果未定义或者为空值,用指定的默认值代替 + * + * @param key key + * @param defaultValue 默认值 + * @author terwer + * @since 0.1.0 + */ +export const getEnvOrDefault = (key: string, defaultValue: string) => { + const value = getEnv(key) + if (value.trim().length == 0) { + return defaultValue + } + return value +} + /** * 获取Boolean类型的环境变量 * @@ -51,10 +62,9 @@ const getEnv = (key: string): string => { * @since 1.0.0 */ const getBooleanEnv = (key: string): boolean => { - let env = false - if (getEnv(key)) { - env = getEnv(key).toLowerCase() === "true" - } + let env: boolean + const defVal = getEnvOrDefault(key, "false") + env = defVal.toLowerCase() === "true" return env }