diff --git a/packages/vite/src/node/plugins/define.ts b/packages/vite/src/node/plugins/define.ts index c22f966257b12d..3eaf2def0efde3 100644 --- a/packages/vite/src/node/plugins/define.ts +++ b/packages/vite/src/node/plugins/define.ts @@ -14,15 +14,12 @@ export function definePlugin(config: ResolvedConfig): Plugin { // ignore replace process.env in lib build const processEnv: Record = {} - const processNodeEnv: Record = {} if (!isBuildLib) { const nodeEnv = process.env.NODE_ENV || config.mode Object.assign(processEnv, { 'process.env': `{}`, 'global.process.env': `{}`, 'globalThis.process.env': `{}`, - }) - Object.assign(processNodeEnv, { 'process.env.NODE_ENV': JSON.stringify(nodeEnv), 'global.process.env.NODE_ENV': JSON.stringify(nodeEnv), 'globalThis.process.env.NODE_ENV': JSON.stringify(nodeEnv), @@ -60,11 +57,10 @@ export function definePlugin(config: ResolvedConfig): Plugin { const replaceProcessEnv = !ssr || config.ssr?.target === 'webworker' const define: Record = { - ...(replaceProcessEnv ? processNodeEnv : {}), + ...(replaceProcessEnv ? processEnv : {}), ...importMetaKeys, ...userDefine, ...importMetaFallbackKeys, - ...(replaceProcessEnv ? processEnv : {}), } // Additional define fixes based on `ssr` value diff --git a/playground/define/__tests__/define.spec.ts b/playground/define/__tests__/define.spec.ts index bdbabb9a52453e..ec1801c7876ca4 100644 --- a/playground/define/__tests__/define.spec.ts +++ b/playground/define/__tests__/define.spec.ts @@ -19,6 +19,9 @@ test('string', async () => { expect(await page.textContent('.process-node-env')).toBe( JSON.parse(defines['process.env.NODE_ENV']), ) + expect(await page.textContent('.process-env')).toBe( + JSON.stringify(defines['process.env'], null, 2), + ) expect(await page.textContent('.env-var')).toBe( JSON.parse(defines['process.env.SOMEVAR']), ) diff --git a/playground/define/index.html b/playground/define/index.html index 4c56dd7674f7a1..2c2898771e5d4e 100644 --- a/playground/define/index.html +++ b/playground/define/index.html @@ -10,6 +10,7 @@

Define

Object

Env Var

process node env:

+

process env:

process as property:

spread object:

spread array:

@@ -68,6 +69,7 @@

Define replaces constants in template literal expressions

text('.undefined', __UNDEFINED__) text('.object', JSON.stringify(__OBJ__, null, 2)) text('.process-node-env', process.env.NODE_ENV) + text('.process-env', JSON.stringify(process.env, null, 2)) text('.env-var', process.env.SOMEVAR) text('.process-as-property', __OBJ__.process.env.SOMEVAR) text( diff --git a/playground/define/vite.config.js b/playground/define/vite.config.js index 49fcdb48bcaabc..997f2b9ae83931 100644 --- a/playground/define/vite.config.js +++ b/playground/define/vite.config.js @@ -20,6 +20,11 @@ export default defineConfig({ }, 'process.env.NODE_ENV': '"dev"', 'process.env.SOMEVAR': '"SOMEVAR"', + 'process.env': { + NODE_ENV: 'dev', + SOMEVAR: 'SOMEVAR', + OTHER: 'works', + }, $DOLLAR: 456, ÖUNICODE_LETTERɵ: 789, __VAR_NAME__: false,