Skip to content

Commit

Permalink
Set dynamic env variables in config file
Browse files Browse the repository at this point in the history
Added an example demonstrating how to set environment variables in the Vite config file.

Included a dynamic setup for the latest Git commit hash (VITE_CODE_VERSION) as an environment variable using execSync. This ensures the app can reference the commit hash during build time
  • Loading branch information
JJAHMEDAMER authored Jan 4, 2025
1 parent da0caf5 commit c7b781e
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions docs/config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,21 @@ export default defineConfig(({ mode }) => {
}
})
```

## Setting Environment Variables inside Config file

Use the define block in Vite to inject global constants or environment variables accessible within the application at build time. While `.env` files should always be used for static variables, dynamic values like the latest Git commit hash can also be set.

```js twoslash
import { defineConfig } from "vite";
import { execSync } from "child_process";

export default defineConfig({
define: {
// Make the commit hash available as an env varaible in your app
"import.meta.env.VITE_CODE_VERSION": JSON.stringify(
execSync("git rev-parse HEAD").toString().trim()
),
},
});
```

0 comments on commit c7b781e

Please sign in to comment.