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

How can I use Vite env variables in vite.config .js?

1个答案

1

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:

plaintext
VITE_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.

javascript
import { 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:

javascript
function 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:
    plaintext
    VITE_API_URL=http://localhost:3000/api
  • .env.production:
    plaintext
    VITE_API_URL=https://prod.example.com/api

In vite.config.js, configure the proxy based on different environment variables:

javascript
server: { 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.

2024年10月27日 17:34 回复

你的答案