Skip to content

docs: add import.meta.env.DEV examples #20352

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions docs/guide/env-and-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,31 @@ Some built-in constants are available in all cases:

- **`import.meta.env.SSR`**: {boolean} whether the app is running in the [server](./ssr.md#conditional-logic).

## Conditional Compilation
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we need a whole section for this. I think a simple example is enough.

:::details Example
```js
if (import.meta.env.DEV) {
  // code inside here will be treeshaken
  console.log('Dev mode') 
}
```
:::


You can include code only in certain modes (for example, only in development, not in production) by wrapping it in conditionals based on Vite's `import.meta.env` values.

For example:

```js
if (import.meta.env.DEV) {
// This code will only run when import.meta.env.DEV is true (in development mode).
console.log('Dev mode only!');
}
```

This is especially useful for including debugging tools or logs only during development, or for excluding code from your production build.

Similarly, you can use `import.meta.env.PROD` for production-only code:

```js
if (import.meta.env.PROD) {
// This code will only run in production mode.
}
```

The conditionals are statically replaced at build time, so code that is only meant for development will not be included in your production bundle, allowing for effective tree-shaking and smaller builds.

## Env Variables

Vite exposes env variables under `import.meta.env` object as strings automatically.
Expand Down
Loading