3

I understand the purpose of %PUBLIC_URL%, however I also understand and have observed that you cannot set PUBLIC_URL and have it replaced during a development (local) run. I have run into the following situation.

I have to reference a script resource which is hosted on a server specific to the deployment environment. I need to grab this resource from a different host, depending on whether this is a development run or is deployed (e.g. QA):

  1. if running locally, then the script needs to come from "https://my-dev-server" (that is, when running locally, the script should be pulled from the DEV environment)
  2. if deployed to DEV, QA, or PROD, then the script needs to come from %PUBLIC_URL%

This already works for deployed environments (#2 above) if I use a script tag such as ...

<script src="%PUBLIC_URL%/a/b/c/my-script.js></script>

However, when running locally, %PUBLIC_URL% is replaced with "" (empty string), so my script is fetched from "/a/b/c/my-script.js" which results in a 404.

How can I have a custom environment variable replaced, e.g. "DEPLOY_HOST", and a script tag like ...

<script src="https://%DEPLOY_HOST%/a/b/c/my-script.js></script>

Note: using react-scripts v2.1.3

Josh M.
  • 26,437
  • 24
  • 119
  • 200

1 Answers1

4

Create two .env file in your root directory

// file name: .env.development
REACT_APP_MY_API=https://dev.api
// file name: .env.production
REACT_APP_MY_API=https://production.api

Please note: In order for this to work the variable names must start with REACT_APP_ otherwise it won't work.

In your index.html, you can do this now:

<script>
  console.log('%REACT_APP_MY_API%'); // This will change based on development or production
</script>

Or you can:

<script src="%REACT_APP_MY_API%/a/b/c/my-script.js"></script>
Max Carroll
  • 4,441
  • 2
  • 31
  • 31
Joseph
  • 3,974
  • 7
  • 34
  • 67
  • Thanks. I was hoping there might be a less clunky way e.g. simply variable replacement, but I'll have to go with something like this. – Josh M. Mar 08 '19 at 17:30
  • @JoshM.I've include another approach, which is a simply variable replacement, it's also a CRA built-in feature. – Joseph Mar 08 '19 at 17:51
  • I tried the variable replacement, just as you have it, but it did not work -- does it require a specific version of react-scripts? – Josh M. Mar 08 '19 at 21:07
  • @JoshM.My bad, I've update whole new answer for you. – Joseph Mar 09 '19 at 05:27
  • it could have perhaps been that the vaiables must begin with `REACT_APP_` otherwise it won't work, I have updated the answer to reflect this – Max Carroll Apr 14 '20 at 10:57