Search code examples
javascripttypescriptvue.jsvite

Property 'env' does not exist on type 'ImportMeta'.ts(2339)


Recently i begin a project using vue.js and vite, everything run normal when using npm run dev but when npm run build its keep give me error Property 'env' does not exist on type 'ImportMeta'.ts(2339)

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue')
    }
 ]
})

// test access to Vite environment variable
console.log(import.meta.env.BASE_URL);

export default router

Here is my env.d.ts

/// <reference types="vite/client" />
interface ImportMeta {
  readonly env: Record<string, string>;
}

here is my tsconfig.json

{
  "files": [],
  "references": [
    {
      "path": "./tsconfig.node.json"
    },
    {
      "path": "./tsconfig.app.json"
    },
    {
      "path": "./tsconfig.vitest.json"
    }
  ],
  "compilerOptions": {
    "module": "NodeNext",
    "allowJs": true,
    "types": ["vite/client"]
  }
}

I have added compiler options, for vite/client but still resulting the same, any guidance or tips will be really useful. I appreciate any response.


Solution

  • In my Vite (^4.4.5) project, I had to include the following line at the top the file from within vite-env.d.ts:

    /// <reference types="vite/types/importMeta.d.ts" />
    

    So the resulting src/vite-env.d.ts, looks like this:

    /// <reference types="vite/client" />
    /// <reference types="vite/types/importMeta.d.ts" />
    

    Note: In my case, I did not need to update my tsconfig.json file to include a reference to vite-env.d.ts, which could be due to the version of Vite (v4) used in this project.