Property 'env' does not exist on type 'ImportMeta' in Vite
Problem Statement
When building Vite projects with TypeScript, developers commonly encounter the error Property 'env' does not exist on type 'ImportMeta'.ts(2339)
. This occurs despite seemingly correct env.d.ts
declarations, preventing successful project builds while access to Vite environment variables like import.meta.env.BASE_URL
works during development.
Solution
Resolve the error through these verified steps:
1. Verify File Setup and Location
Create/update vite-env.d.ts
in your src
directory with:
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_MY_VAR: string
// Add other env variables here
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
2. Configure TypeScript
Update tsconfig.json
to include:
{
"compilerOptions": {
"types": ["vite/client"],
// Other compiler options...
},
"include": [
"src/vite-env.d.ts",
"src/**/*.ts",
"src/**/*.vue"
]
}
3. Check Extended Configurations
Inherited configurations (tsconfig.vitest.json
, tsconfig.app.json
) must not override critical settings. Remove conflicting include
arrays in extended configs if they exist:
// Avoid this in child tsconfigs
"include": ["tests/**/*.ts"]
4. Restart Development Servers
After changes:
- Terminate running processes (
npm run dev
/npm run build
) - Delete
node_modules/.vite
cache - Restart IDE and TypeScript language server
Explanation
- File Location Matters: Vite resolves type definitions primarily from
src/vite-env.d.ts
. Root-level declarations often go undetected. - Configuration Conflicts: Child
tsconfig
files (e.g.,tsconfig.vitest.json
) overridinginclude
can exclude your type declarations. - TypeScript Server Cache: Build tools and IDEs cache type definitions, making restarts essential after configuration changes.
Avoid Suboptimal Workarounds
❌ Don't use // @ts-expect-error
comments – they hide the root issue
❌ Don't place env.d.ts
in project root – use src/
instead
❌ Never delete essential include
arrays – only remove conflicting ones in extended configurations
Final Code Implementation
Correct Environment Access
const baseUrl = import.meta.env.BASE_URL // Error-free access
// src/vite-env.d.ts
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly BASE_URL: string
readonly VITE_API_KEY: string
// Additional variables...
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
Sample tsconfig.app.json
{
"extends": "./tsconfig.json",
"include": ["src/vite-env.d.ts", "src/**/*"]
}
Following these steps ensures TypeScript recognizes Vite's environment variables while maintaining type safety throughout your development and build workflow.