Skip to content

Commit d5fe92c

Browse files
authoredNov 8, 2022
feat(env): support dotenv-expand to contains process env (#10370)
1 parent 8fe3406 commit d5fe92c

File tree

5 files changed

+20
-4
lines changed

5 files changed

+20
-4
lines changed
 

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

+10-3
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,18 @@ export function loadEnv(
4040
)
4141

4242
// let environment variables use each other
43-
dotenvExpand({
44-
parsed,
43+
const expandParsed = dotenvExpand({
44+
parsed: {
45+
...(process.env as any),
46+
...parsed
47+
},
4548
// prevent process.env mutation
4649
ignoreProcessEnv: true
47-
} as any)
50+
} as any).parsed!
51+
52+
Object.keys(parsed).forEach((key) => {
53+
parsed[key] = expandParsed[key]
54+
})
4855

4956
// only keys that start with prefix are exposed to client
5057
for (const [key, value] of Object.entries(parsed)) {

‎playground/env/.env

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
VITE_CUSTOM_ENV_VARIABLE=1
22
CUSTOM_PREFIX_ENV_VARIABLE=1
33
VITE_EFFECTIVE_MODE_FILE_NAME=.env
4-
VITE_BOOL=true
4+
VITE_BOOL=true
5+
VITE_EXPAND=$EXPAND

‎playground/env/__tests__/env.spec.ts

+4
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ test('NODE_ENV', async () => {
4545
expect(await page.textContent('.node-env')).toBe(process.env.NODE_ENV)
4646
})
4747

48+
test('expand', async () => {
49+
expect(await page.textContent('.expand')).toBe('expand')
50+
})
51+
4852
test('env object', async () => {
4953
const envText = await page.textContent('.env-object')
5054
expect(JSON.parse(envText)).toMatchObject({

‎playground/env/index.html

+2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ <h1>Environment Variables</h1>
1414
<p>import.meta.env.VITE_INLINE: <code class="inline"></code></p>
1515
<p>typeof import.meta.env.VITE_BOOL: <code class="bool"></code></p>
1616
<p>process.env.NODE_ENV: <code class="node-env"></code></p>
17+
<p>import.meta.env.VITE_EXPAND: <code class="expand"></code></p>
1718
<p>import.meta.env: <span class="pre env-object"></span></p>
1819
<p>import.meta.url: <span class="pre url"></span></p>
1920

@@ -29,6 +30,7 @@ <h1>Environment Variables</h1>
2930
text('.bool', typeof import.meta.env.VITE_BOOL)
3031
text('.node-env', process.env.NODE_ENV)
3132
text('.env-object', JSON.stringify(import.meta.env, null, 2))
33+
text('.expand', import.meta.env.VITE_EXPAND)
3234

3335
function text(el, text) {
3436
document.querySelector(el).textContent = text

‎playground/env/vite.config.js

+2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
const { defineConfig } = require('vite')
22

3+
process.env.EXPAND = 'expand'
4+
35
module.exports = defineConfig({
46
base: '/env/',
57
envPrefix: ['VITE_', 'CUSTOM_PREFIX_'],

0 commit comments

Comments
 (0)
Please sign in to comment.