How to set build .env variables when running create-react-app build script?

How to Set Build .env Variables When Running create-react-app Build Script?

If you are using create-react-app to build your React application, you might have come across the need to set environment variables specifically for the build process. In this blog post, we will explore different ways to set build .env variables when running the create-react-app build script.

Method 1: Using .env Files

One way to set build .env variables is by using the .env files provided by create-react-app. These files allow you to define environment variables that will be available during the build process.

To set build .env variables, follow these steps:

  1. Create a new file in the root of your React project called .env.production. The .production suffix is important as it specifies that these variables should only be used during the production build.
  2. Inside the .env.production file, define your environment variables in the format VARIABLE_NAME=value. For example, if you want to set a variable called API_URL with the value https://api.example.com, your .env.production file would look like this:
API_URL=https://api.example.com

Once you have defined your environment variables, they will be automatically picked up by create-react-app during the build process.

Method 2: Using Custom Environment Variables

If you prefer to set build .env variables without using the .env files, you can leverage the custom environment variables feature provided by create-react-app.

To set build .env variables using custom environment variables, follow these steps:

  1. Open the package.json file in the root of your React project.
  2. Locate the scripts section and find the build script.
  3. Modify the build script to include the desired environment variables using the REACT_APP_ prefix. For example, if you want to set a variable called API_URL with the value https://api.example.com, your modified build script would look like this:
"build": "REACT_APP_API_URL=https://api.example.com react-scripts build"

Save the changes to the package.json file.

Now, when you run the npm run build command, the specified environment variables will be available during the build process.

Conclusion

Setting build .env variables when running the create-react-app build script can be achieved using either the .env files or custom environment variables. Both methods provide a way to define environment variables specifically for the build process. Choose the method that best suits your project requirements.


Posted

in

by

Tags:

Comments

Leave a Reply

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