3

I have created the react project using vite.

In vite import.meta.env.VITE_SOME_RANDOM_ENV_VARIABLE is used to access the env variables anywhere in our project.

For example in the below code in line number 12.

enter image description here

But my problem is, when i try to access env variables in my vite.config.ts file, i get the following error.

Property 'env' does not exist on type 'ImportMeta'

I also added the image below to show error.

enter image description here

Can you please explain why behaviour is different in vite.config.ts file? I am also adding the importMeta.d.ts file's code below for your reference.

enter image description here

I got the solution here, but can you still explain why the behaviour is different in vite.config.ts file?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Aditya Singh
  • 502
  • 1
  • 5
  • 15

3 Answers3

5

Put this at the top of your vite.config.ts file

/// <reference types="vite/client" />
sandersrd33
  • 61
  • 1
  • 3
3

try this:

// tsconfig.json
{
  "compilerOptions": {
    "types": ["vite/client"]
  }
}
oyal
  • 81
  • 1
  • 3
  • I tried this, did not work for me. [This worked for me](https://stackoverflow.com/questions/66389043/how-can-i-use-vite-env-variables-in-vite-config-js). But still i don't know, why is thiis case with vite.config.ts – Aditya Singh Dec 07 '22 at 09:51
  • 1
    After adding this, I started to see many other type errors appear. Ultimately I had to add `"types": ["vite/client", "@types/node"]` and it worked! – Mark Swardstrom Feb 01 '23 at 16:26
  • Be careful with this solution because you are overriding default types with whatever you specify in the array, which can lead to unexpected results. – thdoan Mar 13 '23 at 01:39
1

Move your vite-env.d.ts file to the root.

  • 1
    While this code snippet may be the solution, including a detailed explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Shawn Hemelstrand Feb 26 '23 at 01:36
  • @ShawnHemelstrand while I do see your point here, I also feel that if someone doesn't understand why config files don't propagate backwards, I am really answering a whole bunch of other questions that weren't asked. I am not trying to be elitist here! – andrewthecoder Feb 26 '23 at 22:58
  • The question is about *vite.config.ts*, and you mention *vite-env.d.ts*; I don't understand how they are related..? If your solution does in fact solve the problem then it'd be incredibly important/ helpful to explain why it does OR link to some documentation that would allow others to understand. Otherwise all it does is add more confusion. – Carlo Nyte Jun 08 '23 at 18:40