I am trying to set the URL of the API at runtime. I followed this tutorial which solves the exact problem I have, but still, the variable is undefined.
I put the file with enviromental variable in script in index.html
(EDITED)
<script src="%PUBLIC_URL%/env-config.js"></script>
Inside of which is (after the image starts through Docker) something like this:
window._env_ = {
API_URL: "my-awesome-url" // filled by bash script defined in ENTRYPOINT
}
But when I want to use it in the React app I get something like cannot read property of undefined API_URL
. When I try to access the window
object in console
, I can see, the _env_
variable is not present in the object. What am I missing?
The script tag is wrong. It is supposed to be like <script src="%PUBLIC_URL%/env-config.js"></script>
Check and try again.
The react environmental variable should be prefixed with word "REACT_" so your variable name should be REACT_PUBLIC_URL and <script src="%REACT_PUBLIC_URL%/env-config.js">
More information can be found here https://dev.to/suprabhasupi/react-environment-variables-k0n
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.