Skip to content

Commit

Permalink
fix: prioritize existing env over .env (fixes #10676) (#10684)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red authored Oct 28, 2022
1 parent 1128b4d commit e2ea6af
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 19 deletions.
30 changes: 22 additions & 8 deletions packages/vite/src/node/__tests__/env.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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",
}
`)
})
})
1 change: 1 addition & 0 deletions packages/vite/src/node/__tests__/env/.env.existing
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_ENV_TEST_ENV=DOTENV
20 changes: 9 additions & 11 deletions packages/vite/src/node/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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], {
Expand Down Expand Up @@ -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
}

Expand Down

0 comments on commit e2ea6af

Please sign in to comment.