Bundle environment variables in Vite at build time startup time!
In Vite, import.meta.env
variables are set at build time with vite build
.
However we often want to enable the person deploying the app to define those values, we don't want to re build every time we need
to change a configuration.
vite-envs
facilitates this by enabling to:
docker run --env FOO="xyz" my-org/my-vite-app
Then, access FOO
:
- In the TypeScript code as
import.meta.env.FOO
- In
index.html
, as<title>%FOO%</title>
This eliminates the need to rebuild each time you wish to change some configuration.
More importantly, it allows you to ship a customizable Docker image of your webapp!
- 🔧 Effortless setup: Integrates smoothly, works as your already used to, does not disrupt your Storybook.
- 😌 The
VITE_
prefix isn't required. - 🛡️ Type-safe: Type definition for your
import.meta.env
. Hot reload enabled! - 🌐
index.html
: Use your envs in your HTML file. Example<title>%FOO%</title>
- 📦
import.meta.env
is an object, not a placeholder.const { FOO } = import.meta.env;
works. - 🧠 Supports computation of env values at build time.
- ⚙️ (Optional) enables to use EJS expressions in your
index.html
.<title><%= import.meta.env.FOO.toUpperCase() =></title>
- 🔒 Secure: Only injects environment variables explicitly defined in the
.env
file.
You can also choose to declare your variables in another file like.env.declaration
if.env
is gitignored in your project.
vite-envs
is a Vite plugin.
When you build your app (vite build
) it generate a dist/vite-envs.sh
script.
When executed, this script updates the dist/index.html
by injecting the environment variables
defined on the host running the script.
Making it work is as easy as updating your Dockerfile
as follows:
Dockerfile
-CMD ["nginx", "-g", "daemon off;"]
+ENTRYPOINT sh -c "./vite-envs.sh && nginx -g 'daemon off;'"
One notable benefit of using cra-envs
is you're getting strict types definitions for import.meta.env
.
Definitions are even hot reloaded!
types-hot-reloading.webm
Onyxia is a Vite app distributed as a Docker image.
Sysadmins that would like to deploy Onyxia on their infrastructure can simply use the official Docker image and provide relevant environnement variable to adjust the theme/branding of the website to their usecase as documented here.
Here are two deployment example: