Skip to content

Commit

Permalink
feat(env): support dotenv-expand to contains process env (#10370)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dunqing committed Nov 8, 2022
1 parent 8fe3406 commit d5fe92c
Show file tree
Hide file tree
Showing 5 changed files with 20 additions and 4 deletions.
13 changes: 10 additions & 3 deletions packages/vite/src/node/env.ts
Expand Up @@ -40,11 +40,18 @@ export function loadEnv(
)

// let environment variables use each other
dotenvExpand({
parsed,
const expandParsed = dotenvExpand({
parsed: {
...(process.env as any),
...parsed
},
// prevent process.env mutation
ignoreProcessEnv: true
} as any)
} as any).parsed!

Object.keys(parsed).forEach((key) => {
parsed[key] = expandParsed[key]
})

// only keys that start with prefix are exposed to client
for (const [key, value] of Object.entries(parsed)) {
Expand Down
3 changes: 2 additions & 1 deletion playground/env/.env
@@ -1,4 +1,5 @@
VITE_CUSTOM_ENV_VARIABLE=1
CUSTOM_PREFIX_ENV_VARIABLE=1
VITE_EFFECTIVE_MODE_FILE_NAME=.env
VITE_BOOL=true
VITE_BOOL=true
VITE_EXPAND=$EXPAND
4 changes: 4 additions & 0 deletions playground/env/__tests__/env.spec.ts
Expand Up @@ -45,6 +45,10 @@ test('NODE_ENV', async () => {
expect(await page.textContent('.node-env')).toBe(process.env.NODE_ENV)
})

test('expand', async () => {
expect(await page.textContent('.expand')).toBe('expand')
})

test('env object', async () => {
const envText = await page.textContent('.env-object')
expect(JSON.parse(envText)).toMatchObject({
Expand Down
2 changes: 2 additions & 0 deletions playground/env/index.html
Expand Up @@ -14,6 +14,7 @@ <h1>Environment Variables</h1>
<p>import.meta.env.VITE_INLINE: <code class="inline"></code></p>
<p>typeof import.meta.env.VITE_BOOL: <code class="bool"></code></p>
<p>process.env.NODE_ENV: <code class="node-env"></code></p>
<p>import.meta.env.VITE_EXPAND: <code class="expand"></code></p>
<p>import.meta.env: <span class="pre env-object"></span></p>
<p>import.meta.url: <span class="pre url"></span></p>

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

function text(el, text) {
document.querySelector(el).textContent = text
Expand Down
2 changes: 2 additions & 0 deletions playground/env/vite.config.js
@@ -1,5 +1,7 @@
const { defineConfig } = require('vite')

process.env.EXPAND = 'expand'

module.exports = defineConfig({
base: '/env/',
envPrefix: ['VITE_', 'CUSTOM_PREFIX_'],
Expand Down

0 comments on commit d5fe92c

Please sign in to comment.