A list of environment variables are available to my Node/FE (Astro based) application via process.env
. I would like to make these also available automatically to my client-side scripts (SSR page, Astro Framework).
Vite offers the possibility to define new global env variables which to my understanding can be available on runtime. This would in theory allow me to use process.env
inside my vite.config, and map these to runtime variables, which I can directly consume from my scripts via import.meta.env
. Is that accurate?
https://vitejs.dev/config/#using-environment-variables-in-config
This is what I'm trying:
// vite config
define: {
stage: process.env.NODE_ENV,
},
And from my client-side script:
console.log(import.meta.env.stage)
Unfortunately, my log is undefined
.
ref : https://vitejs.dev/guide/env-and-mode.html#production-replacement
ref : https://vitejs.dev/config/shared-options.html#envprefix
console.log(import.meta.env.VITE_STAGE)
console.log("True")
Note1 : the client browser does not know import.meta.env.VITE_STAGE
e.g. on browser debug console, it is Vite that replaced the expression on server side with the value
Note2 : all of this is static on build if what was intended was dynamic changing on runtime then see this question https://stackoverflow.com/a/74840400/1324481
You can try,
define: {
'import.meta.env.stage': process.env.NODE_ENV,
},
Unfortunately, I can't find any document about this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With