Fixing the bug where environment variables are not set in bun + vite build
Environment
- vite v3.6.0
- bun v1.0.26
Symptom
When you run the vite build command using bun as the runtime, an environment variable problem occurs. Typically, you use .env files and create multiple .env files for different environments.
For example:
.env.local
.env.development
.env.production
However, when running vite build with bun as the runtime, a bug occurs where the environment variables are always set only from .env.development.
Cause
Both bun and vite provide a feature that reads .env files to set environment variables. But when you run vite through the bun CLI, these features conflict.
Solution
This is actually not a solution but a workaround.
When the above features conflict, vite’s mode parameter works correctly, but it always reads the environment variables from .env.development, or reads the environment variables from the only .env file present in the root directory.
To prevent the conflict between bun’s and vite’s environment variable setting features, make sure that only a single .env file exists in the root path at build time.
// package.json
{
// ...
scripts: {
"build:stage": "cp ./.env/.env.development . && tsc && bunx --bun vite build --mode development",
"build:production": "cp ./.env/.env.production . && tsc && bunx --bun vite build --mode production",
}
// ...
}
The build scripts get a bit messy, but they work as intended.
Other notes
- Manually setting the environment variables one by one in each script in package.json also solves the problem. It just makes the scripts even messier.
- bun simply gives no response at all (issue link)
- vite is turning a blind eye, claiming it’s bun’s problem
- Since no one offered a solution to this bun problem… I just posted a workaround myself.
20240306
Leave a comment