DEV Community

jicking bebiro
jicking bebiro

Posted on

Vite multi-environment setup

Demo Github Repo

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)

Image description

  • Read variable
let envMode = import.meta.env.MODE
let envVariableValue = import.meta.env.VITE_GREETINGS

...

<div>
  Mode: {envMode} <br>
  Variable value: {envVariableValue} <br>
</div>
Enter fullscreen mode Exit fullscreen mode
  • 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"
  },
Enter fullscreen mode Exit fullscreen mode

Reference: https://vitejs.dev/guide/env-and-mode.html#modes

Top comments (0)