@owlpro/react-dotenv
v1.0.7
Published
Load environment variables dynamically for your React applications created with CRA (Create-React-App).
Downloads
4
Maintainers
Readme
react-dotenv
Load environment variables dynamically for your React applications created with create-react-app.
This will create a env.js file in your public and build directories, which will expose your environment variables you want in the global window.env variable.
It will also take care of configuring the index.html file present in those directories to load that file.
Installation
npm install @ludovicm67/react-dotenvUsage
Setup your project
Create a .env file at the root of your project, with some relevant values, like this:
API_URL=https://example.com
SOME_OTHER_VARIABLE=fooOpen your project's package.json file and add:
- the
react-dotenvcommand to yourstartandbuildscripts. - the
react-dotenv.whitelistproperty to specify which variables you need to be exposed.
Here is an example:
package.json:
{
// …other fields
"scripts": {
"start": "react-dotenv && react-scripts start", // <-- append command
"build": "react-dotenv && react-scripts build", // <-- append command
"test": "react-scripts test",
"eject": "react-scripts eject"
},
// …some other fields
// Add the react-dotenv configuration
"react-dotenv": {
"whitelist": ["API_URL"]
}
}Access environment variables from your code
You can start the development server using the following command:
npm run startNow your project have the environment variables loaded globally in the window.env property.
You can access the environment variables from your code in two ways:
Using the @ludovicm67/react-dotenv library
import React from "react";
import env from "@ludovicm67/react-dotenv";
const MyComponent = () => {
return <div>{ env.API_URL }</div>;
};
export default MyComponent;Using the window.env global variable
import React from "react";
const MyComponent = () => {
return <div>{ window.env.API_URL }</div>;
};
export default MyComponent;Known limitations
This only supports one environment (so only one .env file) and is not meant to do more.
Attributions
Forked from jeserodz/react-dotenv.
Reasons:
- upgrade dependencies
- use ESM
- fix TypeScript types
- fix the import of the
env.jsfile in theindex.htmlfiles
