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')