我想从位于根目录下的.env文件访问环境变量,并使用dotenv在我的App.js React文件中使用它们。但是,我无法访问它们。在客户端(App.js)。
我要使用的变量: root / .env
我要在以下位置使用它们的文件: root / client / src / App.js
PORT=5432
TEST=911
REACT_APP_WEATHER=12345678
import './App.css';
require("dotenv").config();
// Doesn't show the variables in the .env file
console.log(process.env);
function App() {
return (
<div className="App">
Hello
</div>
);
}
export default App;
我读到dotenv(安装在我的根目录中)不适用于客户端,而仅适用于服务器端Using environment variables in React。我需要安装该webpack吗?我尝试将其安装在客户端中,但创建了许多错误。
注意:我要将服务器和客户端环境变量存储在同一.env文件中
答案 0 :(得分:-1)
有了 create-react-app
,您就不必使用 dotenv
之类的库。要从 .env
文件中读取数据,您只需在所有变量名称前加上 REACT_APP_
。例如:
REACT_APP_PORT=5432
REACT_APP_TEST=911
REACT_APP_WEATHER=12345678
create-react-app
将在构建期间自动提供给您。在您的 React 应用程序中,您可以随时随地console.log
:
console.log(process.env.REACT_APP_PORT); //5432