Managing Environment Variables in Vite and Resolving Compilation Errors with import.meta.env
Environment File Setup
Establish distinct configuration files for each deployment stage: .env.development, .env.testing, .env.staging, and .env.production. Vite enforces a strict naming convention where exposed variables must begin with the VITE_ prefix.
# Primary endpoint configuration
VITE_API_BASE="https://gateway.staging.cloud"
# Authentication routing token
VITE_SERVICE_TOKEN="stg-auth-7721"
Configuration Integration
Modify the Vite configuration file to dynamically read these values based on the active execution mode. The loadEnv utility parses the appropriate .env file and exposes the parsed object for further processing.
import { defineConfig, loadEnv } from 'vite';
export default defineConfig(({ mode }) => {
const parsedVariables = loadEnv(mode, process.cwd(), '');
return {
define: {
__APP_CONFIG__: {
baseUrl: JSON.stringify(parsedVariables.VITE_API_BASE),
token: JSON.stringify(parsedVariables.VITE_SERVICE_TOKEN)
}
}
};
});
Implementation in Source Code
Once the configuration layer is active, the variables become globally accessible through the import.meta.env namespace. Reference them directly within network modules or initialization scripts.
export const httpClient = {
baseUrl: import.meta.env.VITE_API_BASE,
interceptors: {
request: (config) => {
config.headers['Authorization'] = import.meta.env.VITE_SERVICE_TOKEN;
return config;
}
}
};
Build Workflow Configuration
Define distinct execution commands in the project manifest to trigger environment-specific builds. The --mode flag instructs the bundler to load the corresponding .env file during the compilation phase.
{
"scripts": {
"serve": "vite",
"build": "vite build --max-old-space-size=4096",
"build:testing": "vite build --mode testing --max-old-space-size=4096",
"build:production": "vite build --mode production --max-old-space-size=4096",
"preview:staging": "vite preview --mode staging"
}
}
Executing npm run build:production compiles the application using production variables and optimizes the output bundle accordingly.
Resolving Compilation Errors
Upgrading to Vite 5 often introduces parsing failures when referencing import.meta.env.VITE_* properties. This typically stems from version mismatches between the core bundler and its official plugin ecosystem. Aligning the plugin versions with the core Vite release resolves the static analysis errors.
{
"devDependencies": {
"vite": "^5.0.0",
"@vitejs/plugin-vue": "^5.0.0",
"@vitejs/plugin-vue-jsx": "^4.0.0",
"@vitejs/plugin-legacy": "^5.0.0"
}
}
Synchronize these dependencies and restart the development server. The environment varriables will resolve correctly during the build process without triggering type or syntax errors.