Skip to content

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:

typescript
/// <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:

json
{
  "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:

json
// Avoid this in child tsconfigs
"include": ["tests/**/*.ts"]

4. Restart Development Servers

After changes:

  1. Terminate running processes (npm run dev/npm run build)
  2. Delete node_modules/.vite cache
  3. 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) overriding include 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

typescript
const baseUrl = import.meta.env.BASE_URL // Error-free access
typescript
// 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

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.