fix: prioritize existing env over .env (fixes #10676) (#10684)

This commit is contained in:
翠 / green 2022-10-28 17:06:35 +09:00 committed by GitHub
parent 1128b4dcc9
commit e2ea6afd47
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 32 additions and 19 deletions

View File

@ -9,14 +9,15 @@ describe('loadEnv', () => {
test('basic', () => {
expect(loadEnv('development', join(__dirname, './env')))
.toMatchInlineSnapshot(`
{
"VITE_APP_BASE_ROUTE": "/",
"VITE_APP_BASE_URL": "/",
"VITE_ENV1": "ENV1",
"VITE_ENV2": "ENV2",
"VITE_ENV3": "ENV3",
}
`)
{
"VITE_APP_BASE_ROUTE": "/",
"VITE_APP_BASE_URL": "/",
"VITE_ENV1": "ENV1",
"VITE_ENV2": "ENV2",
"VITE_ENV3": "ENV3",
"VITE_USER_NODE_ENV": "production",
}
`)
})
test('specific prefix', () => {
@ -50,4 +51,17 @@ describe('loadEnv', () => {
loadEnv('development', join(__dirname, './env'))
expect(process.env.VITE_USER_NODE_ENV).toEqual('test')
})
test('prioritize existing process.env', () => {
process.env.VITE_ENV_TEST_ENV = 'EXIST'
expect(loadEnv('existing', join(__dirname, './env')))
.toMatchInlineSnapshot(`
{
"VITE_APP_BASE_ROUTE": "/",
"VITE_APP_BASE_URL": "/",
"VITE_ENV_TEST_ENV": "EXIST",
"VITE_USER_NODE_ENV": "test",
}
`)
})
})

View File

@ -0,0 +1 @@
VITE_ENV_TEST_ENV=DOTENV

View File

@ -24,17 +24,6 @@ export function loadEnv(
/** mode local file */ `.env.${mode}.local`
]
// check if there are actual env variables starting with VITE_*
// these are typically provided inline and should be prioritized
for (const key in process.env) {
if (
prefixes.some((prefix) => key.startsWith(prefix)) &&
env[key] === undefined
) {
env[key] = process.env[key] as string
}
}
const parsed = Object.fromEntries(
envFiles.flatMap((file) => {
const path = lookupFile(envDir, [file], {
@ -69,6 +58,15 @@ export function loadEnv(
process.env.VITE_USER_NODE_ENV = value
}
}
// check if there are actual env variables starting with VITE_*
// these are typically provided inline and should be prioritized
for (const key in process.env) {
if (prefixes.some((prefix) => key.startsWith(prefix))) {
env[key] = process.env[key] as string
}
}
return env
}