env vars in a React Vite app
Useful for dynamically generating tags in the index.html
entry point file.
Define environment variables with VITE_
prefix in .env
file, e.g.
VITE_REACT_APP_VERSION=$npm_package_version
VITE_APP_TITLE="Title of the website"
VITE_APP_DESCRIPTION="React (Vite) app using socket.io and Node.js Express backend"
Then in the index.html
entry point file, the following
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
name="description"
content="%VITE_APP_DESCRIPTION%"
/>
<meta
name="version"
content="%VITE_REACT_APP_VERSION%"
/>
<title>%VITE_APP_TITLE%</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
will generate something like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
name="description"
content="React (Vite) app using socket.io and Node.js Express backend"
/>
<meta
name="version"
content="0.0.0"
/>
<title>Title of the website</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>