Package Exports
- runtime-env-cra
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (runtime-env-cra) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Runtime-env-cra
A runtime environment handler for React.js apps that have been bootstraped using create-react-app.
Usage
- Installation
$ npm install runtime-env-cra- Add the following to
public/index.htmlinside the<head>tag:
<!-- Runtime environment variables -->
<script src="%PUBLIC_URL%/runtime-env.js"></script>- Modify your
startscript to the following in yourpackage.json:
...
"scripts": {
"start": "NODE_ENV=development runtime-env-cra --config-name=./public/runtime-env.js && react-scripts start",
...
}
...The script parses everything based on your .env file and adds it to window.__RUNTIME_CONFIG__.
If you pass NODE_ENV=DEVELOPMENT for the script, it will use the values from your .env, but if you provide anything else than DEVELOPMENT or nothing for NODE_ENV it will parse environment variables from process.env. This way you can dynamically set your environment variables in production/staging environments without the need to rebuild your project.
Requirements
This script uses your .env file by default to parse the environment variables to window.__RUNTIME_CONFIG__, so be sure to have one in your project! After modifying the start script and public/index.html described in the section above, you should be good to go!
CLI options
- Display the help section.
$ runtime-env-cra --help | -h- Relative path and file name that will be generated. Default is
./runtime-env.js
$ runtime-env-cra --config-name | -cn- Relative path and name of your
envfile. Default is./.env
$ runtime-env-cra --env-file | -efTypescript usage
- Create
./src/types/globals.tsfile and pase the following (modify the__RUNTIME_CONFIG__properties to match your environment):
export {};
declare global {
interface Window {
__RUNTIME_CONFIG__: {
API_URL: string;
NODE_ENV: string;
};
}
}- Add
"include": ["src/types"]to yourtsconfig.json.
{
"compilerOptions": { ... },
"include": ["src/types"]
}Usage in Docker
You must have an example of your env layout. A project usually have a .env.example which represents that and will not contain any sensitive information.
Inside a docker container we can lean on the .env.example. Make sure your .env.example is always up to date!
- Using in an alpine based container
# copy .env.example as .env to the container
COPY .env.example .env
# install bash, nodejs & npm
RUN apk add --no-cache bash
RUN apk add --update nodejs
RUN apk add --update npm
# install runtime-env-cra package
RUN npm i -g runtime-env-cra
# start the app with the following CMD
CMD ["/bin/bash", "-c", "runtime-env-cra && nginx -g \"daemon off;\""]