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):
.env.local: Local override, should not be committed to version control.env.[mode].local: Local override for specific mode.env.[mode]: Environment variables for specific mode.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:
javascriptimport { 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 URLimport.meta.env.PROD: Whether it's production environmentimport.meta.env.DEV: Whether it's development environmentimport.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:
- Sensitive information (like API keys) should not be in
.envfiles committed to version control - Use
.env.exampleto provide environment variable templates - Define TypeScript types for environment variables
- Use
VITE_prefix to distinguish client-side and server-side variables - Inject configurations through environment variables in CI/CD