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

How does Vite use environment variables? What are the built-in environment variables?

2月19日 19:14

Vite provides powerful environment variable support, allowing developers to manage configurations for different environments. Here's how to use environment variables in Vite:

Environment Variable Files:

Vite supports the following environment variable files (in priority order from high to low):

  1. .env.local: Local override, should not be committed to version control
  2. .env.[mode].local: Local override for specific mode
  3. .env.[mode]: Environment variables for specific mode
  4. .env: Environment variables common to all environments

Where [mode] can be development, production, or custom mode.

Defining Environment Variables:

bash
# .env VITE_APP_TITLE=My App VITE_API_URL=https://api.example.com # .env.development VITE_API_URL=https://dev-api.example.com # .env.production VITE_API_URL=https://prod-api.example.com

Client-side Access:

Only environment variables prefixed with VITE_ can be accessed in client-side code:

javascript
// In client-side code console.log(import.meta.env.VITE_APP_TITLE) console.log(import.meta.env.VITE_API_URL)

Server-side Access:

All environment variables can be accessed in vite.config.js:

javascript
import { defineConfig, loadEnv } from 'vite' export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd(), '') return { define: { 'import.meta.env.API_URL': JSON.stringify(env.VITE_API_URL) } } })

Built-in Environment Variables:

Vite provides some built-in environment variables:

  • import.meta.env.MODE: Current mode (development/production)
  • import.meta.env.BASE_URL: Deployment base URL
  • import.meta.env.PROD: Whether it's production environment
  • import.meta.env.DEV: Whether it's development environment
  • import.meta.env.SSR: Whether it's server-side rendering

Usage Examples:

javascript
// Configure API based on environment const API_URL = import.meta.env.VITE_API_URL || 'https://api.example.com' // Conditional rendering {import.meta.env.DEV && <DebugPanel />} // Dynamic import const module = import.meta.env.PROD ? await import('./prod-module') : await import('./dev-module')

TypeScript Type Definitions:

typescript
// src/vite-env.d.ts interface ImportMetaEnv { readonly VITE_APP_TITLE: string readonly VITE_API_URL: string } interface ImportMeta { readonly env: ImportMetaEnv }

Best Practices:

  1. Sensitive information (like API keys) should not be in .env files committed to version control
  2. Use .env.example to provide environment variable templates
  3. Define TypeScript types for environment variables
  4. Use VITE_ prefix to distinguish client-side and server-side variables
  5. Inject configurations through environment variables in CI/CD
标签:Vite