From fc4880efbb5a95d45c8d801d847ef89fd5619ca2 Mon Sep 17 00:00:00 2001 From: JJAHMEDAMER <ahmedamer703.aa@gmail.com> Date: Sat, 4 Jan 2025 21:24:31 +0200 Subject: [PATCH] docs(vite): add example for setting environment variables using the define block --- docs/config/index.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/config/index.md b/docs/config/index.md index 0583f69bd52d13..fb43f4864cdbeb 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(), + ), + }, +}) +```