To load environment variables in a React application using Vite, you can use the `vite-env` plugin. This plugin provides support for loading environment variables from `.env` files in your Vite project. Here's how you can set it up:
1. **Install the `vite-env` plugin**:
Install the `vite-env` plugin as a development dependency in your project using npm or yarn:
```bash
npm install --save-dev vite-env
# or
yarn add --dev vite-env
```
2. **Create Environment Variables Files**:
Create one or more `.env` files in the root of your Vite project. You can create different `.env` files for different environments (e.g., `.env.development`, `.env.production`, etc.).
Inside these `.env` files, define your environment variables in the format `VARIABLE_NAME=value`. For example:
```
REACT_APP_API_KEY=your_api_key
REACT_APP_API_URL=https://api.example.com
```
Prefixing your variables with `REACT_APP_` is a convention for React projects to make them available to your React application.
3. **Configure Vite to Use the `vite-env` Plugin**:
In your `vite.config.js` file, import and use the `vite-env` plugin:
```javascript
import env from 'vite-env';
export default {
plugins: [
env(), // Use the vite-env plugin
],
};
```
4. **Access Environment Variables in Your React Application**:
You can now access your environment variables in your React application as follows:
```javascript
// For example, in a React component
const apiKey = import.meta.env.VITE_REACT_APP_API_KEY;
const apiUrl = import.meta.env.VITE_REACT_APP_API_URL;
// Use apiKey and apiUrl in your component
```
The `import.meta.env` object provides access to the environment variables defined in your `.env` files.
5. **Use Different Environment Variables for Different Environments**:
To use different environment variables for different environments (e.g., development, production), create separate `.env` files (e.g., `.env.development`, `.env.production`) and specify which environment you want to build for using Vite's command line options.
For example, to build for production:
```bash
vite build --mode production
```
Vite will use the `.env.production` file when you specify `--mode production`.
By following these steps, you can load environment variables in your React application using Vite and the `vite-env` plugin, which provides a convenient way to manage different sets of variables for different environments.