Skip to content

Commit

Permalink
docs(env): add .env parsing note and vite-env.d.ts augmentation (#15232)
Browse files Browse the repository at this point in the history
Co-authored-by: Bjorn Lu <bjornlu.dev@gmail.com>
  • Loading branch information
iamandrewluca and bluwy committed Dec 4, 2023
1 parent ee12f30 commit 5efbaad
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions docs/guide/env-and-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,15 @@ DB_PASSWORD=foobar
Only `VITE_SOME_KEY` will be exposed as `import.meta.env.VITE_SOME_KEY` to your client source code, but `DB_PASSWORD` will not.

```js
console.log(import.meta.env.VITE_SOME_KEY) // 123
console.log(import.meta.env.VITE_SOME_KEY) // "123"
console.log(import.meta.env.DB_PASSWORD) // undefined
```
:::tip Env parsing
As shown above, `VITE_SOME_KEY` is a number but returns a string when parsed. The same would also happen for boolean env variables. Make sure to convert to the desired type when using it in your code.
:::
Also, Vite uses [dotenv-expand](https://github.com/motdotla/dotenv-expand) to expand variables out of the box. To learn more about the syntax, check out [their docs](https://github.com/motdotla/dotenv-expand#what-rules-does-the-expansion-engine-follow).
Note that if you want to use `$` inside your environment value, you have to escape it with `\`.
Expand All @@ -74,7 +79,7 @@ If you want to customize the env variables prefix, see the [envPrefix](/config/s
By default, Vite provides type definitions for `import.meta.env` in [`vite/client.d.ts`](https://github.com/vitejs/vite/blob/main/packages/vite/client.d.ts). While you can define more custom env variables in `.env.[mode]` files, you may want to get TypeScript IntelliSense for user-defined env variables that are prefixed with `VITE_`.
To achieve this, you can create an `env.d.ts` in `src` directory, then augment `ImportMetaEnv` like this:
To achieve this, you can create an `vite-env.d.ts` in `src` directory, then augment `ImportMetaEnv` like this:
```typescript
/// <reference types="vite/client" />
Expand All @@ -97,6 +102,11 @@ If your code relies on types from browser environments such as [DOM](https://git
}
```
:::warning Imports will break type augmentation
If the `ImportMetaEnv` augmentation does not work, make sure you do not have any `import` statements in `vite-env.d.ts`. See the [TypeScript documentation](https://www.typescriptlang.org/docs/handbook/2/modules.html#how-javascript-modules-are-defined) for more information.
:::
## HTML Env Replacement
Vite also supports replacing env variables in HTML files. Any properties in `import.meta.env` can be used in HTML files with a special `%ENV_NAME%` syntax:
Expand Down

0 comments on commit 5efbaad

Please sign in to comment.