Skip to content

Commit e2ea6af

Browse files
authoredOct 28, 2022
fix: prioritize existing env over .env (fixes #10676) (#10684)
1 parent 1128b4d commit e2ea6af

File tree

3 files changed

+32
-19
lines changed

3 files changed

+32
-19
lines changed
 

‎packages/vite/src/node/__tests__/env.spec.ts

+22-8
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,15 @@ describe('loadEnv', () => {
99
test('basic', () => {
1010
expect(loadEnv('development', join(__dirname, './env')))
1111
.toMatchInlineSnapshot(`
12-
{
13-
"VITE_APP_BASE_ROUTE": "/",
14-
"VITE_APP_BASE_URL": "/",
15-
"VITE_ENV1": "ENV1",
16-
"VITE_ENV2": "ENV2",
17-
"VITE_ENV3": "ENV3",
18-
}
19-
`)
12+
{
13+
"VITE_APP_BASE_ROUTE": "/",
14+
"VITE_APP_BASE_URL": "/",
15+
"VITE_ENV1": "ENV1",
16+
"VITE_ENV2": "ENV2",
17+
"VITE_ENV3": "ENV3",
18+
"VITE_USER_NODE_ENV": "production",
19+
}
20+
`)
2021
})
2122

2223
test('specific prefix', () => {
@@ -50,4 +51,17 @@ describe('loadEnv', () => {
5051
loadEnv('development', join(__dirname, './env'))
5152
expect(process.env.VITE_USER_NODE_ENV).toEqual('test')
5253
})
54+
55+
test('prioritize existing process.env', () => {
56+
process.env.VITE_ENV_TEST_ENV = 'EXIST'
57+
expect(loadEnv('existing', join(__dirname, './env')))
58+
.toMatchInlineSnapshot(`
59+
{
60+
"VITE_APP_BASE_ROUTE": "/",
61+
"VITE_APP_BASE_URL": "/",
62+
"VITE_ENV_TEST_ENV": "EXIST",
63+
"VITE_USER_NODE_ENV": "test",
64+
}
65+
`)
66+
})
5367
})
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
VITE_ENV_TEST_ENV=DOTENV

‎packages/vite/src/node/env.ts

+9-11
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,6 @@ export function loadEnv(
2424
/** mode local file */ `.env.${mode}.local`
2525
]
2626

27-
// check if there are actual env variables starting with VITE_*
28-
// these are typically provided inline and should be prioritized
29-
for (const key in process.env) {
30-
if (
31-
prefixes.some((prefix) => key.startsWith(prefix)) &&
32-
env[key] === undefined
33-
) {
34-
env[key] = process.env[key] as string
35-
}
36-
}
37-
3827
const parsed = Object.fromEntries(
3928
envFiles.flatMap((file) => {
4029
const path = lookupFile(envDir, [file], {
@@ -69,6 +58,15 @@ export function loadEnv(
6958
process.env.VITE_USER_NODE_ENV = value
7059
}
7160
}
61+
62+
// check if there are actual env variables starting with VITE_*
63+
// these are typically provided inline and should be prioritized
64+
for (const key in process.env) {
65+
if (prefixes.some((prefix) => key.startsWith(prefix))) {
66+
env[key] = process.env[key] as string
67+
}
68+
}
69+
7270
return env
7371
}
7472

0 commit comments

Comments
 (0)
Please sign in to comment.