I am trying to set up build-specific environment variables for use in our front-end (not NodeJS) ReactJS application initialised using create-react-app.
I have created three files in my project root: .env, .env.development, .env.production
For testing purposes I have put these variables in each .env file:
REACT_APP_TEST_KEY=1
TEST_KEY=1
And in my app.js file in the render function, I have added these debug lines:
console.log(`.env test key: ${process.env.REACT_APP_TEST_KEY}`);
console.log(`.env test key: ${process.env.TEST_KEY}`);
After saving all, I then run npm start at the command line.
The result is as follows:
.env test key: undefined
.env test key: undefined
As you can see I have tried to hedge on the subject of whether one should or should not be using the prepend REACT_APP.
I have spent hours reviewing the various blog posts on this subject, as well as the two most popular questions asked on SO on this subject, and I still don't feel I have an answer, especially as some of the responses confuse whether it'll work only in node and not in the browser, and that the create-react-app documentation some same has not been updated.
That documentation, btw, clearly implies that this should run out of the box with no additional edits to the package.json file. I've included it below, in any case:
"name": "ui",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"msal": "^1.3.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.1.2",
"react-scripts": "3.4.1",
"react-stl-obj-viewer": "^1.2.0"
},
"scripts": {
"start": "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",
"ie 11"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version",
"ie 11"
]
},
"devDependencies": {
"node-sass": "^4.13.1"
}