It is not
possible to dynamically inject Vite
env variables. But what is possible, is to change the window object
variables (assign them on runtime).
WARNING!!! DO NOT EXPOSE ANY SENSITIVE VARIABLES THROUGH THE WINDOW OBJECT. YOUR FRONT-END APPLICATION SOURCE IS VISIBLE TO ANYONE USING IT
Steps:
Create your desired env files and place them in <rootDir>/public
. Let's call them env.js
and env-prod.js
.
Inside your env.js
and env-prod.js
You want to assign your desired variables using var
keyword. Also, you will have to reference these values in your source like window.MY_VAR
to be able to use them.
Create a script tag inside your <rootDir>/index.html
like this:
<script type="text/javascript" src="./env.js"></script>
.
IMPORTANT!!! type="text/javascript"
is important, because if You specify module, Vite
will include your env.js
source inside your minified index.js
file.
Vite config (optional):
plugins: [react(), tsConfigPath()],
build: {
emptyOutDir: true, // deletes the dist folder before building
},
});
How to serve the env files on runtime
. Create a node
server which will serve your frontend application. But before serving the env.js
file, depending on our process.env.ENVIRONMENT
you can now choose which env.js to serve. Let's say my node server file is stored at <rootDir>/server/server.js
:
const express = require("express");
const path = require("path");
const app = express();
const env = process.env.ENVIRONMENT || "";
console.log("ENVIRONMENT:", env);
const envFile = path.resolve("public", env ? `env-${env}.js` : "env.js");
const indexFile = path.resolve("dist", "index.html");
app.use((req, res, next) => {
const url = req.originalUrl;
if (url.includes("env.js")) {
console.log("sending", envFile);
// instead of env.js we send our desired env file
res.sendFile(envFile);
return;
}
next();
});
app.use(express.static(path.resolve("dist")));
app.get("*", (req, res) => {
res.sendFile(indexFile);
});
app.listen(8000);
Serve your application build while running node ./server/sever.js
command in your terminal.
Finally:
my env.js
contains var RUNTIME_VAR = 'test'
my env-prod.js
contains var RUNTIME_VAR = 'prod'
After I set my process.env.ENVIRONMENT
to prod
. I get this file served:
