diff --git a/packages/vite/src/node/optimizer/index.ts b/packages/vite/src/node/optimizer/index.ts index 36503d4ee37f5e..df54a0c9ae98ed 100644 --- a/packages/vite/src/node/optimizer/index.ts +++ b/packages/vite/src/node/optimizer/index.ts @@ -775,9 +775,11 @@ async function prepareEsbuildOptimizerRun( if (optimizerContext.cancelled) return { context: undefined, idToExports } const define = { - 'process.env.NODE_ENV': JSON.stringify( - process.env.NODE_ENV || environment.config.mode, - ), + 'process.env.NODE_ENV': environment.config.keepProcessEnv + ? // define process.env.NODE_ENV even for keepProcessEnv === true + // as esbuild will replace it automatically when `platform` is `'browser'` + 'process.env.NODE_ENV' + : JSON.stringify(process.env.NODE_ENV || environment.config.mode), } const platform = @@ -1210,7 +1212,9 @@ function getConfigHash(environment: Environment): string { const { optimizeDeps } = config const content = JSON.stringify( { - mode: process.env.NODE_ENV || config.mode, + define: config.keepProcessEnv + ? process.env.NODE_ENV || config.mode + : null, root: config.root, resolve: config.resolve, assetsInclude: config.assetsInclude, diff --git a/playground/environment-react-ssr/__tests__/environment-react-ssr.spec.ts b/playground/environment-react-ssr/__tests__/environment-react-ssr.spec.ts index 3bf14f6e4f5eca..03cce7ebfd42cc 100644 --- a/playground/environment-react-ssr/__tests__/environment-react-ssr.spec.ts +++ b/playground/environment-react-ssr/__tests__/environment-react-ssr.spec.ts @@ -40,6 +40,25 @@ describe.runIf(!isBuild)('pre-bundling', () => { expect(metaJson.optimized['react/jsx-dev-runtime']).toBeTruthy() expect(metaJson.optimized['react-dom/client']).toBeFalsy() + + // process.env.NODE_ENV should be kept as keepProcessEnv is true + const depsFiles = fs + .readdirSync(path.resolve(testDir, 'node_modules/.vite/deps_ssr'), { + withFileTypes: true, + }) + .filter((file) => file.isFile() && file.name.endsWith('.js')) + .map((file) => path.join(file.parentPath, file.name)) + const depsFileHasProcessEnvNodeEnvLeft = depsFiles + .filter((file) => + fs.readFileSync(file, 'utf-8').includes('process.env.NODE_ENV'), + ) + .map((file) => + path.relative( + path.resolve(testDir, 'node_modules/.vite/deps_ssr'), + file, + ), + ) + expect(depsFileHasProcessEnvNodeEnvLeft.length).toBeGreaterThan(0) }) test('deps reload', async () => {