Skip to content

Instantly share code, notes, and snippets.

@an1meshk
Last active September 3, 2021 03:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save an1meshk/e6d8659ec1ad0b7bdfee153269312d9b to your computer and use it in GitHub Desktop.
Save an1meshk/e6d8659ec1ad0b7bdfee153269312d9b to your computer and use it in GitHub Desktop.
react-runtime-variables
window._env_ = {
REACT_APP_RUNTIME_PROD_KEY=abc
};
REACT_APP_RUNTIME_PREPROD_KEY=xyz
#!/bin/bash
# look for runtime env file
if [ ! -z "${2}" ]; then
envFile="${1}"/env."${2}"
fi
#If can't find it then exit
if [[ ! -f "$envFile" ]]; then
echo "Env file doesn't exist!"
exit 1;
fi
# create runtime env JS file
if [[ ! -z "${1}" ]]; then
envJs="${1}/env-config.js"
fi
#Recreate config file
rm -rf ${envJs}
touch ${envJs}
# Add assignment
echo "window._env_ = {" >> ${envJs}
# Read each line in .env file
# Each line represents key=value pairs
while read -r line || [[ -n "$line" ]];
do
# Split env variables by character `=`
if printf '%s\n' "$line" | grep -q -e '='; then
varname=$(printf '%s\n' "$line" | sed -e 's/=.*//')
varvalue=$(printf '%s\n' "$line" | sed -e 's/^[^=]*=//')
fi
# Read value of current variable if exists as Environment variable
value=$(printf '%s\n' "${!varname}")
# Otherwise use value from .env file
[[ -z $value ]] && value=${varvalue}
# Append configuration property to JS file
echo " $varname: \"$value\"," >> ${envJs}
done < ${envFile}
echo "};" >> "${envJs}"
echo "generated ${envJs} with content"
cat ${envJs}
<head>
<script src="%PUBLIC_URL%/env/env-config.js?d=20210529"></script>
</head>
location ~ /env/(.+\.(?:js))$ {
expires -1;
add_header Cache-Control "public"
}
"prestart" : "chmod +x ./public/env/env.sh && ./public/env/env.sh ./public/env preprod"
bash ./public/env/env.sh ./public/env preprod
const API_KEY = window._env_?.REACT_APP_RUNTIME_PROD_KEY ? window._env_.REACT_APP_RUNTIME_PROD_KEY : window._env_.REACT_APP_RUNTIME_PREPROD_KEY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment