I used create-react-app to generate a node app. I changed the app.js file to look like this:
import React from 'react';
import logo from './logo.svg';
import './App.css';
let a = process.env.SOMETHING;
console.log(a)
function App() {
console.log(process.env)
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
{ process.env.SOMETHING }
</a>
</header>
<div>The value of something: ${a}</div>
</div>
);
}
I would expect the a
variable to reflect what I set in the environment. When I look at the console after starting the app, it is undefined, and all I see is the dollar sign where the variable should be inserted.
I've tried setting the variable in two ways. Firstly, I created a bash file called setup.bash
and gave it executable permission. It looks like this:
setup.bash
export SOMETHING="boom"
Then I changed package.json
to this:
{
"name": "server",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.10.2",
"react-dom": "^16.10.2",
"react-scripts": "3.2.0"
},
"scripts": {
"start": "./setup.bash && react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
When this didn't work, I tried starting the app like this:
SOMETHING=BOOM npm start
... and the environment variable remained undefined.
Can anyone see what the problem might be?
Create .env.development
text file.
Then you can list variables there, but all of them must start with REACT_APP_
prefix.
For example:
REACT_APP_API_URL=https://api.url
You can also run the npm start
command with variables declared before it:
REACT_APP_API_URL="https://api.url" npm start
, but again, remember about the prefix.
Read more about environment variable for create-react-app here.
It did not work for me after I set REACT_APP_API_URL=https://api.url
in .env
Then I stop react-app, runnpm start
and it works fine for me.
Don't forget create .env
in the root directory
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With