Skip to content

Instantly share code, notes, and snippets.

@angie
Created September 17, 2021 15:17
Show Gist options
  • Save angie/4e651a07544f6067bd288da24c2e5a47 to your computer and use it in GitHub Desktop.
Save angie/4e651a07544f6067bd288da24c2e5a47 to your computer and use it in GitHub Desktop.
#!/bin/sh
# Take REACT_APP_* env vars and make them available at runtime
# Simplified version of https://www.freecodecamp.org/news/how-to-implement-runtime-environment-variables-with-create-react-app-docker-and-nginx-7f9d42a91d70/
set -euo pipefail
# Recreate config file
rm -rf ./env-config.js
touch ./env-config.js
# Add assignment
echo "window.env_config = {" >> ./env-config.js
# Dump all REACT env vars in to a file
# Each line represents key=value pairs
tempenv="$(env | grep REACT_APP_ | sort || true)" # Stop the script failing if grep doesn't find anything
echo "$tempenv" > .env
# Read each line in .env file
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/^[^=]*=//')
# Append configuration property to JS file
echo " $varname: \"$varvalue\"," >> ./env-config.js
fi
done < .env
echo "}" >> ./env-config.js
@angie
Copy link
Author

angie commented Sep 17, 2021

thanks @loveboat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment