From d87bef9611222aca2b2f6c5d67cb6c39eed1a429 Mon Sep 17 00:00:00 2001 From: Vladimir Date: Tue, 2 Jul 2024 10:44:32 +0200 Subject: [PATCH] fix(vite-node): expose all envs from .env file, not just with a prefix `VITE_` (#6017) --- packages/vite-node/src/cli.ts | 8 +++++++- test/vite-node/.env.local | 1 + test/vite-node/src/cli-print-env.js | 2 ++ test/vite-node/test/cli.test.ts | 6 ++++++ 4 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 test/vite-node/.env.local create mode 100644 test/vite-node/src/cli-print-env.js diff --git a/packages/vite-node/src/cli.ts b/packages/vite-node/src/cli.ts index 3da521eed0e7..88913197e874 100644 --- a/packages/vite-node/src/cli.ts +++ b/packages/vite-node/src/cli.ts @@ -1,7 +1,7 @@ import { resolve } from 'node:path' import cac from 'cac' import c from 'picocolors' -import { createServer } from 'vite' +import { createServer, loadEnv } from 'vite' import { version } from '../package.json' import { ViteNodeServer } from './server' import { ViteNodeRunner } from './client' @@ -95,6 +95,12 @@ async function run(files: string[], options: CliOptions = {}) { }) await server.pluginContainer.buildStart({}) + const env = loadEnv(server.config.mode, server.config.envDir, '') + + for (const key in env) { + process.env[key] ??= env[key] + } + const node = new ViteNodeServer(server, serverOptions) installSourcemapsSupport({ diff --git a/test/vite-node/.env.local b/test/vite-node/.env.local new file mode 100644 index 000000000000..36f26df57274 --- /dev/null +++ b/test/vite-node/.env.local @@ -0,0 +1 @@ +MY_TEST_ENV=hello \ No newline at end of file diff --git a/test/vite-node/src/cli-print-env.js b/test/vite-node/src/cli-print-env.js new file mode 100644 index 000000000000..ab18c4a82187 --- /dev/null +++ b/test/vite-node/src/cli-print-env.js @@ -0,0 +1,2 @@ +// eslint-disable-next-line no-console +console.log(JSON.stringify(process.env, null, 2)) diff --git a/test/vite-node/test/cli.test.ts b/test/vite-node/test/cli.test.ts index 0b48d168e41f..fea9d13800bb 100644 --- a/test/vite-node/test/cli.test.ts +++ b/test/vite-node/test/cli.test.ts @@ -39,6 +39,12 @@ it('script args in -- after', async () => { expect(parseResult(cli1.stdout)).include('--version').include('--help') }) +it('exposes .env variables', async () => { + const { stdout } = await runViteNodeCli(resolve(__dirname, '../src/cli-print-env.js')) + const env = JSON.parse(stdout) + expect(env.MY_TEST_ENV).toBe('hello') +}) + it.each(['index.js', 'index.cjs', 'index.mjs'])('correctly runs --watch %s', async (file) => { const entryPath = resolve(__dirname, '../src/watch', file) const { viteNode } = await runViteNodeCli('--watch', entryPath)