This fixes the long standing problem of having the environment variables during runtime available.
- facebook/create-react-app#578 (comment).
- https://vanja.gavric.org/blog/configure-create-react-app-to-consume-env-variables-during-run-time/
We have a create-react-app, which is put into a container and deployed on multiple servers. Right now running yarn build will consume all
environment variables - this means, we could run yarn build only at docker start. This increases the startup time to nearly 2 minutes.
- Should not influcence running
yarn startat all - this means, the ".env" file, ".env.local" and environment variables should still be usable. - Minimal influence on the existing code-base
- No dependencies, so that it can be run easily in docker (meaning: bash-scripts)
- at build-time (
yarn build) all environment variables are reset to a placeholder variable- Only those variables listed inside .env are replaced (and only those starting with
REACT_)
- Only those variables listed inside .env are replaced (and only those starting with
- at run-time (nginx, serve) all placeholders are replaced with the environment variables
- Only those variables inside the environment are replaced (not those from .env)
Included in this repository is a small create-react-app sample application. Another sample application (sample_nginx) uses nginx and a
staged building process - just to show that this still works (just modify the entrypoint.sh to use nginx).
Because of the treeshaking of uglify, statements such as if (process.env.REACT_APP_VAR1 === "Y") must be rewritten - otherwise this
statement is evaluated at compile-time. This would then evaluate to if (@REACT_APP_VAR1@ === "Y") and remove the statement.
The solution is quite simple - confuse the treeshaker with a method-call:
Either use .valueOf() or .toString():
if (process.env.REACT_APP_VAR1.valueOf() === "Y")
This is only needed when the variable is used in comparisons - if they are purely used as a string (e.g., name of the application, url to the backend, there is no need to use valuOf()).