Skip to content

Commit

Permalink
fix: put envs from .env files on process.env (#770)
Browse files Browse the repository at this point in the history
Co-authored-by: patak <matias.capeletto@gmail.com>
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
3 people committed Feb 17, 2022
1 parent 6d19bf7 commit 1623b3c
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
13 changes: 9 additions & 4 deletions packages/vitest/src/node/plugins/index.ts
Expand Up @@ -62,14 +62,19 @@ export async function VitestPlugin(options: UserConfig = {}, ctx = new Vitest())
)
options.api = resolveApiConfig(options)

process.env.BASE_URL ??= viteConfig.base
process.env.MODE ??= viteConfig.mode
// we replace every "import.meta.env" with "process.env"
// to allow reassigning, so we need to put all envs on process.env
const { PROD, DEV, ...envs } = viteConfig.env

// process.env can have only string values and will cast string on it if we pass other type,
// so we are making them truthy
process.env.PROD ??= viteConfig.env.PROD ? '1' : ''
process.env.DEV ??= viteConfig.env.DEV ? '1' : ''
process.env.PROD ??= PROD ? '1' : ''
process.env.DEV ??= DEV ? '1' : ''
process.env.SSR ??= '1'

for (const name in envs)
process.env[name] ??= envs[name]

// account for user env defines
for (const key in viteConfig.define) {
if (key.startsWith('import.meta.env.')) {
Expand Down
1 change: 1 addition & 0 deletions test/core/.env.local
@@ -0,0 +1 @@
VITE_TEST_ENV=local
4 changes: 4 additions & 0 deletions test/core/test/env.test.ts
@@ -1,6 +1,10 @@
import { expect, test } from 'vitest'
import { getAuthToken } from '../src/env'

test('reads envs from .env file', () => {
expect(import.meta.env.VITE_TEST_ENV).toBe('local')
})

test('can reassign env locally', () => {
import.meta.env.VITEST_ENV = 'TEST'
expect(import.meta.env.VITEST_ENV).toBe('TEST')
Expand Down

0 comments on commit 1623b3c

Please sign in to comment.