How to set environment variables in React with Webpack

Today we will show you how to set environment variables in React with Webpack configuration. We will also show you how to load different environment variables from the .env files based on the development/production build.

If you are working with the create-react-app then we will recommend you to check the article to set environment variables in React.

Here, we will explain two different ways to set environment variables in a react webpack project.

Two different ways to set environment variables

  1. Use the DefinePlugin to set environment variables
  2. Use an .env file to set environment variables

1. Use the DefinePlugin to set environment variables

The DefinePlugin will be used to create a global variable which can be configured at compile time. We can use the DefinePlugin in webpack.config.js file under plugins. Look at the following sample code.

webpack.config.js

Now you can directly use the variable to access the value in the react app.

2. Use an .env file to set environment variables

Let’s assume that you have two different environments to run the react project such as development & production environments.

To load different values based on the environment configurations, we need to create two separate .env files to set the environment variables.

Follow the below project structure.

File Structure

  • react-project
    • environments
      • .env
      • .env.development
    • package.json
    • webpack.config.js

First of all, create two different files.

  • .env – Define all the environment variables for production.
  • .env.development – Define all the environment variables for development.
.env
.env.development

Now, We have to use the dotenv-webpack npm package to load the .env file and set the environment variables. Run the following command to install the package.

Let’s update the webpack.config.js file.

webpack.config.js

At last, use the following script to load the environment variables.

package.json

Run one of the following command based on the environment.

  • npm run build – To load the production environment.
  • npm run build:dev – To load the development environment.

After running the above command, you need to use the process.env.FOO or process.env.API_URL variable to access the value.

You may also like this article: How to pass webpack environment variables in HTML

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

1 Response

  1. Amandeep says:

    I am getting this error
    Error: Unknown option ‘–env.file=development’

Leave a Reply

Your email address will not be published. Required fields are marked *