乐闻世界logo
搜索文章和话题

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

1个答案

1

When using create-react-app to build a React application, you can set environment variables by creating a .env file at the root of the project. Environment variables in the .env file must start with REACT_APP_. This is create-react-app's convention to ensure that only variables prefixed with REACT_APP_ are included in the built application.

If you want to define specific variables during the build process, follow these steps:

  1. Create a new file named .env at the root of the project.
  2. Add environment variables to the .env file, ensuring they start with REACT_APP_, for example:
REACT_APP_API_URL
REACT_APP_FEATURE_FLAG=true``` 3. In your React code, you can access these variables using `process.env.REACT_APP_API_URL` and `process.env.REACT_APP_FEATURE_FLAG`. If you need to configure different variables for various environments (development, testing, production), you can create environment-specific `.env` files, such as: - `.env.local`: Local development environment variables. - `.env.development`: Development environment variables. - `.env.test`: Testing environment variables. - `.env.production`: Production environment variables. When you run `npm run build` or `yarn build`, the `create-react-app` build script will default to using variables from `.env.production`. For instance, to set an API URL in the production environment, you can: 1. Create a `.env.production` file at the root of the project. 2. Add the following content: ```REACT_APP_API_URL=https://production.api.com``` 3. When you run the build script, `REACT_APP_API_URL` will be set to `https://production.api.com`. Ensure that you do not include sensitive information (such as passwords or API keys) in the `.env` file before committing code to a version control system (e.g., Git). Typically, this sensitive information should be provided securely, such as through environment variables configured in CI/CD pipelines.
2024年6月29日 12:07 回复

你的答案