ENV variable replacement in HTML using Vite
Assuming a fresh install of Vite via npm create vite@latest
, add a .env
file to your project and add a test variable, for example…
VITE_TEST_KEY=123
Note that the the prefix VITE_
is significant, only variables prefixed in this way will be exposed to the client.
To prevent accidentally leaking env variables to the client, only variables prefixed with VITE_ are exposed to your Vite-processed code.
.env Files
For html env replacement use the syntax %ENV_NAME%
. The following example shows the VITE_TEST_KEY
variable in index.html
, the default index file generated by vite.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="test" content="%VITE_TEST_KEY%" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + TS</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
If you run the app you will see the generated markup has the replaced value which occurs at build time.
<meta name="test" content="123">
Nice and easy.