简体   繁体   English

使用 vite 在反应应用程序中加载环境变量

[英]loading env variables in react app using vite

I´ve been through all the docs from vite, react.js and dev blogs, but I'm not getting it to work我已经浏览了来自 vite、react.js 和 dev 博客的所有文档,但我没有让它工作

I have a.env file which contains the following我有一个 .env 文件,其中包含以下内容

VITE_API_KEY = XXX 

inside my firebase.js file I'm loading it like:在我的 firebase.js 文件中,我正在加载它:

const firebaseConfig = {
  apiKey: import.meta.env.API_KEY,
   .....
   .....
}
// Initialize Firebase
const app = initializeApp(firebaseConfig);

but it appears as null , I've restarted the dev server, reinstalled node_modules (just in case) changed var prefixes to REACT_APP_XX, tried using process.env.XX global object, basically gone through all different ways to read vars from a.env file in react但它显示为null ,我重新启动了开发服务器,重新安装了 node_modules(以防万一)将 var 前缀更改为 REACT_APP_XX,尝试使用 process.env.XX 全局 object,基本上通过所有不同的方式从 a.env 读取 var反应中的文件

I´ve also tried to clog it from a component but it has the same result我也尝试过从组件中阻塞它,但结果相同

any suggestions/methods to solve this problem?有什么建议/方法来解决这个问题?

The environment variable name used in code must match the name set in the .env file:代码中使用的环境变量名称必须与.env文件中设置的名称匹配:

// .env
VITE_API_KEY=abcd1234
   👆
// firebase.js
const firebaseConfig = {      👇
  apiKey: import.meta.env.VITE_API_KEY,
  ⋮
}

demo 演示

finally solved this problem, the thing was that:终于解决了这个问题,问题是:

import.meta.env.VITE_XX

this env variable are statically replaced during production, not development, at least in my case I solved this by checking the mode by doing这个环境变量在生产过程中被静态替换,而不是开发,至少在我的情况下,我通过检查模式解决了这个问题

 if(import.meta.env.MODE === "development"){
//use dev keys
}
else{
//use .env variables
}

when in production mode处于生产模式时

import.meta.env.VITE_XX 

variables will load correctly, so you can add them as env variables in your deployment service and it will work fine.变量将正确加载,因此您可以将它们作为环境变量添加到部署服务中,它会正常工作。 I've tested it with vercel and it worked我已经用vercel对其进行了测试,并且有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM