An issue arises when attempting to retrieve environment variables solely during runtime. If the goal is to modify your index.html
file based on the environment before execution, a somewhat clunky solution exists:
The workaround involves "swapping" the current index.html
with an alternative version located in a separate source (directory). Each index.html
contains the necessary HTML and JavaScript components. To execute this file swapping process, a build.sh
script with instructions or a build.js
file for those who prefer NodeJS can be utilized. Subsequently, your npm run build
command will resemble: "build": "node build.js"
.
Below you will find a rudimentary example of a build.js
script from one of my older projects (although not ideal, it got the job done):
const mv = require("mv");
const spawn = require("cross-spawn");
console.log("Preparing environment for build...");
mv("public", "_public", err => {
if (err) console.log(err);
});
mv("build", "public", err => {
if (err) console.log(err);
});
console.log("Building...");
const build = spawn.sync("npm", ["run", "prod"]);
console.log(`stderr: ${build.stderr.toString()}`);
console.log(`stdout: ${build.stdout.toString()}`);
console.log("Reverting environment back to development...");
mv("public", "build", err => {
if (err) console.log(err);
});
new Promise((resolve, reject) => {
mv("_public", "public", reject);
resolve();
}).then(() => {
console.log("Done!");
});