Here's a quick personal public post on setting/reading env variables on Vite.
By default, Vite uses Development env mode when running on local then switches to Production on Build. For demonstration I will add a staging mode since I use it on most projects I'm working on.
- Create env files with vars corresponds to environment (I have staging here)
- Read variable
let envMode = import.meta.env.MODE
let envVariableValue = import.meta.env.VITE_GREETINGS
...
<div>
Mode: {envMode} <br>
Variable value: {envVariableValue} <br>
</div>
- Update script to run on specific environment mode (package.json)
"scripts": {
"start": "vite",
"start:staging": "vite --mode staging",
"start:production": "vite --mode production",
"build": "vite build",
"build:staging": "vite build --mode staging",
"preview": "vite preview"
},
Top comments (0)