Skip to content

Instantly share code, notes, and snippets.

@nathanKramer
Created September 26, 2019 00:14
Show Gist options
  • Save nathanKramer/5695dc755e946d22e3c43056beaa3d3d to your computer and use it in GitHub Desktop.
Save nathanKramer/5695dc755e946d22e3c43056beaa3d3d to your computer and use it in GitHub Desktop.
How to configure `create-react-app` `PUBLIC_URL` for use in a re-usable slug / container

Usage:

PUBLIC_URL={{DYNAMIC_PUBLIC_URL}}
DYANMIC_PUBLIC_URL=https://my-environment-specific-public-url.com
  • PUBLIC_URL is used at build time by CRA. index.html will contain the literal string {{DYNAMIC_PUBLIC_URL}}
  • DYNAMIC_PUBLIC_URL is used at startup time to perform a find and replace on the string {{DYNAMIC_PUBLIC_URL}}, wherever it is found in index.html

.profile.d/inject-dynamic-public-url.sh

#
# Usage:
# ```
# PUBLIC_URL={{DYNAMIC_PUBLIC_URL}}
# DYANMIC_PUBLIC_URL=https://my-environment-specific-public-url.com
# ```
#
# There is nothing magic about the `{{}}`, as we are just doing a find and replace.
# We could use any string we wanted, but I think using a conventional template syntax makes it easier to understand what is happening.
#
# If `PUBLIC_URL` is set to an actual URL, this is a no-op, so will work fine.
# If `PUBLIC_URL` is set to the template value, but no `DYNAMIC_PUBLIC_URL` is set, it is equivalent to no `PUBLIC_URL` being set,
# Which works fine: `<script src="/static/js/main.7726234d.chunk.js"></script>`
#
if [ -f "build/index.html" ]; then
  sed -iE "s,{{DYNAMIC_PUBLIC_URL}},$DYNAMIC_PUBLIC_URL,g" build/index.html
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment