Skip to content

Commit

Permalink
fix(optimizer): keep NODE_ENV as-is when keepProcessEnv is true (#1…
Browse files Browse the repository at this point in the history
…8899)

Co-authored-by: Dario Piotrowicz <dario.piotrowicz@gmail.com>
  • Loading branch information
sapphi-red and dario-piotrowicz authored Dec 16, 2024
1 parent 7d6dd5d commit 8a6bb4e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
12 changes: 8 additions & 4 deletions packages/vite/src/node/optimizer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,19 @@ 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 depsFilesWithProcessEnvNodeEnv = depsFiles.filter((file) =>
fs.readFileSync(file, 'utf-8').includes('process.env.NODE_ENV'),
)

expect(depsFilesWithProcessEnvNodeEnv.length).toBeGreaterThan(0)
})

test('deps reload', async () => {
Expand Down

0 comments on commit 8a6bb4e

Please # to comment.