react-inject-env
is a tool that allows you to inject your environment variables after building the static files, allowing you to deploy the same build to multiple environments quickly.
Create a new file called env.js
, and place all your process.env
variables here.
export const env = {
REACT_APP_COLOR: process.env.REACT_APP_COLOR,
REACT_APP_LOGO_URL: process.env.REACT_APP_LOGO_URL,
REACT_APP_MAIN_TEXT: process.env.REACT_APP_MAIN_TEXT,
REACT_APP_LINK_URL: process.env.REACT_APP_LINK_URL
}
When referencing environment variables, import env
and reference it from there instead. Do not access process.env
directly from now on.
import { env } from './env'
export const App = () => {
return (
<div style={{backgroundColor: env.REACT_APP_COLOR}}>
<span>{env.REACT_APP_MAIN_TEXT}</span>
</div>
)
}
[env variable names] npx react-inject-env build [your build script]
Pass in all your environment variable names (the value does not matter), then run npx react-inject-env build
, followed by your build script.
# if your build script is 'npm run build'
REACT_APP_COLOR= REACT_APP_TEXT= npx react-inject-env build npm run build
# if your build script is 'react-scripts build'
REACT_APP_COLOR= REACT_APP_TEXT= npx react-inject-env build react-scripts-build
[env variables] react-inject-env inject -d [path to build folder] -o [new output path]
Pass in all your environment variables, followed by the path to your build folder in Step #2
, and the new output path for the static files that will contain the injected environment variables.
# with a black background
REACT_APP_COLOR=black REACT_APP_TEXT="Black Background" npx react-inject-env inject -d build -o build-black
# with a blue background
REACT_APP_COLOR=blue REACT_APP_TEXT="Blue Background" npx react-inject-env inject -d build -o build-blue
.env
files are supported. react-inject-env
will automatically detect environment variables in your .env
file located in your root folder.
Note: Environment variables passed in through the command line will take precedence over .env
variables.
FROM node:16.10-slim
COPY . /app
WORKDIR /app
RUN npm install
RUN \
REACT_APP_COLOR= \
REACT_APP_LOGO_URL= \
REACT_APP_MAIN_TEXT= \
REACT_APP_LINK_URL= \
npx react-inject-env build npm run build
EXPOSE 8080
ENTRYPOINT \
REACT_APP_COLOR=$REACT_APP_COLOR \
REACT_APP_LOGO_URL=$REACT_APP_LOGO_URL \
REACT_APP_MAIN_TEXT=$REACT_APP_MAIN_TEXT \
REACT_APP_LINK_URL=$REACT_APP_LINK_URL \
npx react-inject-env inject -d ./build \
&& npx http-server build
Note: There is no need to use the -o
parameter in Docker.