Description
Describe the bug
I was thinking it is a critical issue but when recreating the minimal reproducible PoC for the issue I found the root cause.
I still think this should be resolved even if it is more related to the developer's mistake than a bug.
Long story short;
I was looking to use process.env. in the vite.config.js file and I found this example https://stackoverflow.com/a/70711383 but that response is not compatible with the current vite at all and will create all sorts of issues if used in dev mode.
// !!! DO NOT USE !!!
import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
// https://vitejs.dev/config/
export default ({ mode }) => {
process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };
console.log(process.env);
return defineConfig({
plugins: [react()],
});
};
The issue lies in the mutation of the process.env object because as soon as the process.env is set loadEnv will not override the values from process.env
// This is fine but not ideal
import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
// https://vitejs.dev/config/
export default ({ mode }) => {
const env = { ...process.env, ...loadEnv(mode, process.cwd()) };
console.log(env);
return defineConfig({
plugins: [react()],
});
};
The reason I'm opening this as a bug is as I see the way to resolve this issue such that it works in both cases, and this doesn't seem like intended behaviour, we could save the state of process.env at the first run of the server and consider this for the last loop in loadEnv for subsequent server reloads, making snippet valid. As this is only used to prioritise inline env vars according to the comment.
I've also left updated solution on StackOverflow
Reproduction
https://stackblitz.com/edit/vitejs-vite-wrbmyr?file=.env
Steps to reproduce
No response
System Info
System:
OS: Linux 5.0 undefined
CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
Memory: 0 Bytes / 0 Bytes
Shell: 1.0 - /bin/jsh
Binaries:
Node: 18.20.3 - /usr/local/bin/node
Yarn: 1.22.19 - /usr/local/bin/yarn
npm: 10.2.3 - /usr/local/bin/npm
pnpm: 8.15.6 - /usr/local/bin/pnpm
npmPackages:
vite: ^5.3.2 => 5.3.3
Used Package Manager
npm
Logs
No response
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- Make sure this is a Vite issue and not a framework-specific issue. For example, if it's a Vue SFC related bug, it should likely be reported to vuejs/core instead.
- Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- The provided reproduction is a minimal reproducible example of the bug.