Skip to content

Commit c7b781e

Browse files
authored
Set dynamic env variables in config file
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
1 parent da0caf5 commit c7b781e

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

docs/config/index.md

+18
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,21 @@ export default defineConfig(({ mode }) => {
115115
}
116116
})
117117
```
118+
119+
## Setting Environment Variables inside Config file
120+
121+
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.
122+
123+
```js twoslash
124+
import { defineConfig } from "vite";
125+
import { execSync } from "child_process";
126+
127+
export default defineConfig({
128+
define: {
129+
// Make the commit hash available as an env varaible in your app
130+
"import.meta.env.VITE_CODE_VERSION": JSON.stringify(
131+
execSync("git rev-parse HEAD").toString().trim()
132+
),
133+
},
134+
});
135+
```

0 commit comments

Comments
 (0)