Environment variables help you configure your application for different environments (e.g., development, testing, and production). Using environment variables in the vite.config.js file allows you to flexibly adjust configurations based on different environments.
Step 1: Create Environment Variable Files
First, create environment variable files in the project's root directory. Vite natively supports .env files and allows you to create specific files for different environments, such as .env.development, .env.production, etc.
For example, create the .env.development file and add the following content:
plaintextVITE_API_URL=http://localhost:3000/api VITE_APP_TITLE=My Vite App - Development
Step 2: Configure vite.config.js
In the vite.config.js file, you can access environment variables via import.meta.env. Note that Vite requires environment variables to start with VITE_ to be accessible on the client side.
javascriptimport { defineConfig } from 'vite'; export default defineConfig({ // Configure different base public paths using environment variables base: import.meta.env.VITE_APP_BASE_URL || '/', // Other configurations... server: { proxy: { '/api': { target: import.meta.env.VITE_API_URL, changeOrigin: true, secure: false, } } } });
Step 3: Use Environment Variables
In your application code, you can also access these environment variables via import.meta.env. For example, in a React component to display the application title:
javascriptfunction AppHeader() { return <h1>{import.meta.env.VITE_APP_TITLE}</h1>; }
Example
Suppose you are developing an application that needs to call a backend API. In the development environment, you might want to route requests to a local development server, whereas in production, you would route them to the production server. You can achieve this by setting different environment variables, as follows:
.env.development:plaintextVITE_API_URL=http://localhost:3000/api.env.production:plaintextVITE_API_URL=https://prod.example.com/api
In vite.config.js, configure the proxy based on different environment variables:
javascriptserver: { proxy: { '/api': { target: import.meta.env.VITE_API_URL, changeOrigin: true, secure: false, } } }
Thus, when running the application in the development environment, all /api requests will be proxied to the local development server; when deployed in production, they will point to the production server's API.
Conclusion
By doing this, Vite allows you to flexibly use environment variables to adjust application configurations based on different environments, which is an effective method for managing large application configurations.