From c7b781ef29d8d163614bcd48d68c3b95a0562963 Mon Sep 17 00:00:00 2001 From: Ahmed Amer Date: Sat, 4 Jan 2025 20:45:50 +0200 Subject: [PATCH] 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 --- docs/config/index.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/config/index.md b/docs/config/index.md index 0583f69bd52d13..f1fb63b7704978 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -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() + ), + }, +}); +```