Skip to content

Commit d0ebe36

Browse files
docs(config): clarify environment variable loading in Vite config (#20624)
Co-authored-by: 翠 <[email protected]>
1 parent 9ee86bf commit d0ebe36

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

docs/config/index.md

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,11 @@ export default defineConfig(async ({ command, mode }) => {
101101

102102
## Using Environment Variables in Config
103103

104-
Environmental Variables can be obtained from `process.env` as usual.
104+
Environment variables available while the config itself is being evaluated are only those that already exist in the current process environment (`process.env`). Vite deliberately defers loading any `.env*` files until _after_ the user config has been resolved because the set of files to load depends on config options like [`root`](/guide/#index-html-and-project-root) and [`envDir`](/config/shared-options.md#envdir), and also on the final `mode`.
105105

106-
Note that Vite doesn't load `.env` files by default as the files to load can only be determined after evaluating the Vite config, for example, the `root` and `envDir` options affect the loading behaviour. However, you can use the exported `loadEnv` helper to load the specific `.env` file if needed.
106+
This means: variables defined in `.env`, `.env.local`, `.env.[mode]`, or `.env.[mode].local` are **not** automatically injected into `process.env` while your `vite.config.*` is running. They _are_ automatically loaded later and exposed to application code via `import.meta.env` (with the default `VITE_` prefix filter) exactly as documented in [Env Variables and Modes](/guide/env-and-mode.html). So if you only need to pass values from `.env*` files to the app, you don't need to call anything in the config.
107+
108+
If, however, values from `.env*` files must influence the config itself (for example to set `server.port`, conditionally enable plugins, or compute `define` replacements), you can load them manually using the exported [`loadEnv`](/guide/api-javascript.html#loadenv) helper.
107109

108110
```js twoslash
109111
import { defineConfig, loadEnv } from 'vite'
@@ -114,10 +116,14 @@ export default defineConfig(({ mode }) => {
114116
// `VITE_` prefix.
115117
const env = loadEnv(mode, process.cwd(), '')
116118
return {
117-
// vite config
118119
define: {
120+
// Provide an explicit app-level constant derived from an env var.
119121
__APP_ENV__: JSON.stringify(env.APP_ENV),
120122
},
123+
// Example: use an env var to set the dev server port conditionally.
124+
server: {
125+
port: env.APP_PORT ? Number(env.APP_PORT) : 5173,
126+
},
121127
}
122128
})
123129
```

0 commit comments

Comments
 (0)