I have a React 18 application using create-react-app. I'm using Visual Studio code for my ide. I have two .env files in my root folder (not in my scr folder). Both of them hold the same environment variable.
In my .env file I have the variable's value set to false:
REACT_APP_IS_CONSOLELOG=false
In my .env.development file I have the variable's value set to true:
REACT_APP_IS_CONSOLELOG=true
I then launch the application in Visual Studio code in a new terminal using npm-start. In my *.tsx file I output the following to the console:
console.log(process.env);
console.log(process.env.REACT_APP_IS_CONSOLELOG);
For the first statement I see this:
{NODE_ENV: 'development', PUBLIC_URL: '', WDS_SOCKET_HOST: undefined, WDS_SOCKET_PATH: undefined, WDS_SOCKET_PORT: undefined, …}
For the second statement I see "false." I am expecting to see "true" for the second statement. React is reading the environment variable from my ".env" file, instead of from my ".env.development" file. What am I doing wrong? When I run the application on my local host I want React to use environment variables from my .env.development file, not from my .env file.
According to the React documentation at https://create-react-app.dev/docs/adding-custom-environment-variables/#adding-development-environment-variables-in-env, my setup should work.
Following a link in the documentation, I saw an instruction to install "dotenv", which I did, but it still does not work.
This is what my package.jason dependencies looks like:
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.11.64",
"@types/react": "^18.0.21",
"@types/react-dom": "^18.0.6",
"dotenv": "^16.0.3",
"jest-editor-support": "^30.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-error-boundary": "^3.1.4",
"react-query": "^3.39.2",
"typescript": "^4.8.4",
"uuid": "^9.0.0",
"web-vitals": "^2.1.4"
},
This is what my package.json scripts looks like; in the "start" setting I'm loading a local ssl cert, and then calling "react-scripts start".
"scripts": {
"start": "set HTTPS=true&&set SSL_CRT_FILE=C:/Users/MyName/Documents/Certificates/cert.crt&&set SSL_KEY_FILE=C:/Users/MyName/Documents/Certificates/cert.key&&react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
CodePudding user response:
Add “.env.development” to the “react-scripts start” command in the “scripts” setting in package.json.
The “scripts” setting should look like this:
"scripts": {
"start": "set HTTPS=true&&set SSL_CRT_FILE=C:/Users/MyName/Documents/Certificates/cert.crt&&set SSL_KEY_FILE=C:/Users/MyName/Documents/Certificates/cert.key&&react-scripts start .env.development",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
Remove “dotenv” from the dependencies setting, it is redundant.