admin管理员组文章数量:1334327
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?
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?
2 Answers
Reset to default 3First 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
I cannot fully explain why, but what was working for me when facing the same issue is to make sure of 2 things:
- All env variables need to have the prefix VITE_ (you have that)
- the .env file needs to be in the in the root directory of the project
(Yours seem to be placed in the /src folder, which is one level below root)
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.
本文标签: javascriptHow to use an env variable in Vite with TypescriptStack Overflow
版权声明:本文标题:javascript - How to use an .env variable in Vite with Typescript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742369135a2461881.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论