From 68d75a540ec8b3168c3af956ea00b898036d92cd Mon Sep 17 00:00:00 2001 From: Ben Lin <maobin001@msn.com> Date: 星期四, 04 七月 2024 00:17:17 +0800 Subject: [PATCH] 包装规则更新 --- internal/vite-config/src/utils/env.ts | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 49 insertions(+), 0 deletions(-) diff --git a/internal/vite-config/src/utils/env.ts b/internal/vite-config/src/utils/env.ts new file mode 100644 index 0000000..c84ea94 --- /dev/null +++ b/internal/vite-config/src/utils/env.ts @@ -0,0 +1,49 @@ +import { join } from 'node:path'; + +import dotenv from 'dotenv'; +import { readFile } from 'fs-extra'; + +/** + * 鑾峰彇褰撳墠鐜涓嬬敓鏁堢殑閰嶇疆鏂囦欢鍚� + */ +function getConfFiles() { + const script = process.env.npm_lifecycle_script as string; + const reg = new RegExp('--mode ([a-z_\\d]+)'); + const result = reg.exec(script); + if (result) { + const mode = result[1]; + return ['.env', `.env.${mode}`]; + } + return ['.env', '.env.production']; +} + +/** + * Get the environment variables starting with the specified prefix + * @param match prefix + * @param confFiles ext + */ +export async function getEnvConfig( + match = 'VITE_GLOB_', + confFiles = getConfFiles(), +): Promise<{ + [key: string]: string; +}> { + let envConfig = {}; + + for (const confFile of confFiles) { + try { + const envPath = await readFile(join(process.cwd(), confFile), { encoding: 'utf8' }); + const env = dotenv.parse(envPath); + envConfig = { ...envConfig, ...env }; + } catch (e) { + console.error(`Error in parsing ${confFile}`, e); + } + } + const reg = new RegExp(`^(${match})`); + Object.keys(envConfig).forEach((key) => { + if (!reg.test(key)) { + Reflect.deleteProperty(envConfig, key); + } + }); + return envConfig; +} -- Gitblit v1.9.3