From 95c16a5d26f9fd9a1d11894afe1146ca495eee93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=91=A8=E6=97=AD?= Date: Wed, 30 Jun 2021 00:49:19 +0800 Subject: [PATCH] fix: support various vite modes of build, not just production (#832) (cherry picked from commit bcc4773fbfc3dd1b7a24655bc731be830ad6d72d) --- build/utils.ts | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/build/utils.ts b/build/utils.ts index a3059f66990..4a0ce500f70 100644 --- a/build/utils.ts +++ b/build/utils.ts @@ -39,22 +39,37 @@ export function wrapperEnv(envConf: Recordable): ViteEnv { return ret; } +/** + * 获取当前环境下生效的配置文件名 + */ +function getConfFiles() { + const script = process.env.npm_lifecycle_script; + const reg = new RegExp('--mode ([a-z]+) '); + const result = reg.exec(script as string) as any; + if (result) { + const mode = result[1] as string; + return ['.env', `.env.${mode}`]; + } + return ['.env', '.env.production']; +} + /** * Get the environment variables starting with the specified prefix * @param match prefix * @param confFiles ext */ -export function getEnvConfig(match = 'VITE_GLOB_', confFiles = ['.env', '.env.production']) { +export function getEnvConfig(match = 'VITE_GLOB_', confFiles = getConfFiles()) { let envConfig = {}; confFiles.forEach((item) => { try { const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item))); envConfig = { ...envConfig, ...env }; - } catch (error) {} + } catch (e) { + console.error(`Error in parsing ${item}`, e); + } }); - + const reg = new RegExp(`^(${match})`); Object.keys(envConfig).forEach((key) => { - const reg = new RegExp(`^(${match})`); if (!reg.test(key)) { Reflect.deleteProperty(envConfig, key); }