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:
- 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. - Inside the
.env.production
file, define your environment variables in the formatVARIABLE_NAME=value
. For example, if you want to set a variable calledAPI_URL
with the valuehttps://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:
- Open the
package.json
file in the root of your React project. - Locate the
scripts
section and find thebuild
script. - Modify the
build
script to include the desired environment variables using theREACT_APP_
prefix. For example, if you want to set a variable calledAPI_URL
with the valuehttps://api.example.com
, your modifiedbuild
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.
Leave a Reply