For example you want to put build time to your reactjs app. Edit package.json
like that:
"scripts": {
"start": "REACT_APP_BUILD_TIME=$(date +%s) react-app-rewired start",
"build": "REACT_APP_BUILD_TIME=$(date +%s) react-app-rewired build"
}
You can use REACT_APP_BUILD_TIME
variable in public/index.html
file. For example:
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico?%REACT_APP_BUILD_TIME%" />
You must wrap env variable with %
characters. And there is another rule: you must add REACT_APP_
to your env variable. You can not add other env variables to react app.
How can you add all .env
variables to reactjs app?
You can use env-cmd
package for this.
yarn add env-cmd
"scripts": {
"start": "REACT_APP_BUILD_TIME=$(date +%s) ./node_modules/.bin/env-cmd react-app-rewired start",
"build": "REACT_APP_BUILD_TIME=$(date +%s) ./node_modules/.bin/env-cmd react-app-rewired build"
}
Example .env
content:
REACT_APP_NAME="My React App"
REACT_APP_API_ENDPOINT=https://127.0.0.1:8080/api
REACT_APP_SOCKETIO_ENDPOINT=http://127.0.0.1:3333
After that you can add these variables to your public/index.html
file like that:
<script>
window.env.REACT_APP_NAME = "%REACT_APP_NAME%";
window.env.REACT_APP_API_ENDPOINT = "%REACT_APP_API_ENDPOINT%";
window.env.REACT_APP_SOCKETIO_ENDPOINT = "%REACT_APP_SOCKETIO_ENDPOINT%";
</script>
In reactjs side you can use these variables like that:
alert(window.env.REACT_APP_SOCKETIO_ENDPOINT);
That's all.
Edit: Normally there is no this property: window.env
but we set this now for easy to use. You can assign your env variables to anywhere in index.html
file.