Reputation: 607
I've an .env
file with the following variable:
VITE_GIPHY_KEY=abcdfg
And I'm trying to use that .env
variable in src/main.ts
like this:
console.log(import.meta.env.VITE_GIPHY_KEY);
I get undefined
in the console. How can I use .env
variables in Vite with TS?
Upvotes: 2
Views: 9878
Reputation: 81
I cannot fully explain why, but what was working for me when facing the same issue is to make sure of 2 things:
I assume the reason that .env.local works must be because the builder expects the .env in the absolute path, but the .env.locals in relative paths to root. I am sure someone more knowledgable can give a more detailed answer.
Per the docs, there is also a envDir variable that can be set. I assume this will change where the builder looks for .env files. E.g. if you want to have all your .env files in a folder like /envs.
Upvotes: 2
Reputation: 607
First I renamed .env
to .env.local
Second, only variables prefixed with VITE_
are exposed to your Vite-processed code.
Example:
VITE_SOME_KEY=123
DB_PASSWORD=foobar
console.log(import.meta.env.VITE_SOME_KEY) // 123
console.log(import.meta.env.DB_PASSWORD) // undefined
Source: https://vitejs.dev/guide/env-and-mode.html#env-files
Upvotes: 3