From 1623b3c985364821f75a1d53ed499b74f47c63a6 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Thu, 17 Feb 2022 11:24:17 +0300 Subject: [PATCH] fix: put envs from .env files on process.env (#770) Co-authored-by: patak Co-authored-by: Anthony Fu --- packages/vitest/src/node/plugins/index.ts | 13 +++++++++---- test/core/.env.local | 1 + test/core/test/env.test.ts | 4 ++++ 3 files changed, 14 insertions(+), 4 deletions(-) create mode 100644 test/core/.env.local diff --git a/packages/vitest/src/node/plugins/index.ts b/packages/vitest/src/node/plugins/index.ts index 7f5e055b445c..b1962c4f09c4 100644 --- a/packages/vitest/src/node/plugins/index.ts +++ b/packages/vitest/src/node/plugins/index.ts @@ -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.')) { diff --git a/test/core/.env.local b/test/core/.env.local new file mode 100644 index 000000000000..e47f042f539a --- /dev/null +++ b/test/core/.env.local @@ -0,0 +1 @@ +VITE_TEST_ENV=local \ No newline at end of file diff --git a/test/core/test/env.test.ts b/test/core/test/env.test.ts index ec28127c55bc..7557c4930000 100644 --- a/test/core/test/env.test.ts +++ b/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')