Environment variable usage issue
Basic Concepts of Environment Variables
Vite.js uses environment variables to manage configurations across different environments. Environment variables are key-value pairs injected into the application during build time or runtime, typically used to store sensitive or environment-specific information such as API endpoints and feature flags. Vite follows the dotenv specification and supports the .env
file loading mechanism.
Environment variable files are usually placed in the project root directory and named according to specific rules:
.env
- Common to all environments.env.development
- Development environment.env.production
- Production environment.env.local
- Local overrides (git-ignored)
# .env.development
VITE_API_URL=https://dev.api.example.com
VITE_DEBUG_MODE=true
Environment Variable Loading Mechanism
Vite automatically loads environment variable files matching the current mode when starting up. The loading order follows these rules:
.env
- Base configuration.env.[mode]
- Mode-specific configuration.env.[mode].local
- Local override configuration
In development mode (using the vite
command), the default mode is development
. During builds (using vite build
), the default mode is production
. A custom mode can be specified using the --mode
parameter:
vite --mode staging
Using Environment Variables in Client-Side Code
Only variables prefixed with VITE_
will be statically replaced by Vite and exposed to client-side code. This prevents accidental leakage of sensitive information. In client-side code, access them via the import.meta.env
object:
// Get the base API URL
const apiUrl = import.meta.env.VITE_API_URL;
// Check if in development environment
const isDev = import.meta.env.MODE === 'development';
// Get the base URL of the application
const baseUrl = import.meta.env.BASE_URL;
TypeScript Type Support
For better type hints, create an env.d.ts
file in the src
directory for type declarations:
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_URL: string
readonly VITE_APP_TITLE: string
// More environment variables...
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
Build-Time Replacement
Vite performs static replacement during the build process, meaning environment variable values are directly replaced in the final code. For example:
// Source code
console.log(import.meta.env.VITE_API_URL);
// After build, it may become
console.log("https://prod.api.example.com");
Multi-Environment Configuration Practices
In real-world projects, managing configurations for multiple environments is often necessary. A recommended approach is:
- Create a base configuration file
.env
- Create specific files for each environment:
.env.development
.env.staging
.env.production
- Use
vite.config.js
to dynamically load configurations
// vite.config.js
import { defineConfig, loadEnv } from 'vite'
export default defineConfig(({ mode }) => {
// Load all environment variables
const env = loadEnv(mode, process.cwd(), '')
return {
// Use environment variables in configuration
define: {
__APP_VERSION__: JSON.stringify(env.VITE_APP_VERSION)
}
}
})
Environment Variable Security Considerations
- Do not commit sensitive information: Ensure
.env.local
and files containing sensitive information are in.gitignore
- Prefix restriction: Only variables prefixed with
VITE_
are exposed to the client - Server-side variables: Node.js environment variables are still accessed via
process.env
- Value type handling: All environment variable values are converted to strings
# Unsafe practice (variables will be exposed to the client)
API_KEY=12345
# Safe practice
VITE_PUBLIC_KEY=12345
Custom Environment Variable Prefix
To modify the default VITE_
prefix, set it in the configuration file:
// vite.config.js
export default defineConfig({
envPrefix: 'APP_' // Now only variables prefixed with APP_ will be exposed
})
Environment Variables and HTML Templates
Environment variables can be used in index.html
, and Vite will replace them:
<title>%VITE_APP_TITLE%</title>
Test Environment Handling
Test environments (e.g., Jest) may require special handling of environment variables:
// jest.config.js
module.exports = {
setupFiles: ['<rootDir>/tests/setupEnv.js']
}
// tests/setupEnv.js
process.env.VITE_API_URL = 'http://test.api.example.com'
Environment Variable Validation
It is recommended to use libraries like envalid
for environment variable validation:
// src/utils/env.ts
import { cleanEnv, str, bool } from 'envalid'
export const env = cleanEnv(import.meta.env, {
VITE_API_URL: str(),
VITE_DEBUG_MODE: bool({ default: false })
})
Dynamic Environment Variables
In some cases, environment variables need to be set dynamically at runtime:
// Override environment variables via URL parameters
const urlParams = new URLSearchParams(window.location.search)
if (urlParams.has('apiUrl')) {
import.meta.env.VITE_API_URL = urlParams.get('apiUrl')
}
Environment Variables and Docker Integration
In Docker environments, use the --env-file
parameter to specify environment variable files:
FROM node:16
WORKDIR /app
COPY package*.json .
RUN npm install
COPY . .
CMD ["npm", "run", "dev", "--", "--host"]
Start command:
docker run --env-file .env.production -p 3000:3000 my-vite-app
Environment Variables and CI/CD Integration
In CI/CD pipelines, environment variables can be set via steps:
# GitHub Actions example
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npm install
- run: npm run build
env:
VITE_API_URL: ${{ secrets.PRODUCTION_API_URL }}
Environment Variable Performance Optimization
A large number of environment variables may impact build performance. Recommendations:
- Only expose necessary variables to the client
- Avoid using environment variable checks in hot paths
- For immutable configurations, consider using regular configuration files
// Not recommended (reads environment variables every time)
function getConfig() {
return import.meta.env.VITE_CONFIG
}
// Recommended (replaced with a constant during build)
const CONFIG = import.meta.env.VITE_CONFIG
function getConfig() {
return CONFIG
}
Environment Variable Debugging Tips
For debugging environment variable issues:
- View the complete environment object in the console
console.log(import.meta.env)
- Check variable replacement in the built code
- Use Vite's
--debug
flag to see which environment files are loaded
vite --debug
Environment Variables and SSR
Note the following in SSR builds:
// Server entry
import { createServer } from 'vite'
const server = await createServer({
server: {
middlewareMode: true
}
})
// Server can access process.env
console.log(process.env.SSR_ONLY_VAR)
Environment Variables and Proxy Configuration
Environment variables can be used in development server proxy configurations:
// vite.config.js
export default defineConfig({
server: {
proxy: {
'/api': {
target: import.meta.env.VITE_PROXY_TARGET,
changeOrigin: true
}
}
}
})
Environment Variables and Feature Flags
Common patterns for implementing feature flags:
// Environment configuration
VITE_FEATURE_NEW_DASHBOARD=true
// Usage in code
if (import.meta.env.VITE_FEATURE_NEW_DASHBOARD === 'true') {
renderNewDashboard()
} else {
renderLegacyDashboard()
}
Environment Variables and Internationalization
Manage multilingual configurations with environment variables:
// .env
VITE_DEFAULT_LOCALE=en
VITE_SUPPORTED_LOCALES=en,fr,de
// Usage in code
const locales = import.meta.env.VITE_SUPPORTED_LOCALES.split(',')
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:路径别名相关问题
下一篇:CSS作用域问题处理