I have a React application that utilizes environment variables. I need to build this React app along with its environment variables because I am unable to set these variables during runtime. The reason is that I am rendering the built React application using ReactDOM within an Angular application.
Inside the react package.json file, the scripts section looks like this:
"build": "env-cmd -f ./.env.development.js microbundle-crl --compress --format modern,cjs --jsxFragment React.Fragment"
Based on other solutions, I added react-error-overlay
(versions 6.0.10 and 6.0.9) and react-scripts
(versions 4.0.3, 4.0.1, and 5.0.0). I attempted the following configuration:
"overrides": {
"react-error-overlay": "6.0.10"
},
"resolutions": {
"react-error-overlay": "6.0.10"
}
None of the above solutions worked for me. However, when I hardcode the environment variables, it works as expected.
The environment file looks as follows:
const version = require('./package.json').version
module.exports = {
AP_URL: 'http://localhost:10500'
}
2
Answers
Your env files should be dot text files, not javascript
You can follow this example
.env.development
Example how to use your env variable in code
I’ve gotten this to work using only
env-cmd
on a minimal reproducible example:App.js
environment.js
package.json
If you use these code samples on a basic
create-react-app
project you can see that the environment variable namedIGNORED_VAR
gets ignored in the build simply because it doesn’t start withREACT_APP
. This is a safety measure to prevent injecting unrelated variables in builds as stated in the docs.It seems to me that the variable names in your environment file are not prepended by
REACT_APP
and, if I am not mistaken, your build script is missing thebuild
command.