Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from Oct 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 22 additions & 8 deletions packages/vite/src/node/__tests__/env.spec.ts
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
@@ -0,0 +1 @@
VITE_ENV_TEST_ENV=DOTENV
20 changes: 9 additions & 11 deletions packages/vite/src/node/env.ts
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