反应环境变量 .env 返回未定义 [英] react evironment variables .env return undefined
问题描述
我正在构建一个 React 应用程序,我需要从我的 api 中获取数据,现在我想将 api url 存储为环境变量.我有我的 .env 文件,我安装了 dotenv,这是我的代码 process.env.API_URL 返回 undefined.
import React, { Component } from 'react';从'./logo.svg'导入标志;导入'./App.css';从../src/components/Home"导入主页从 'dotenv' 导入 dotenv从路径"导入路径类 App 扩展组件 {使成为() {控制台日志(process.env.API_URL)返回 (<div><主页/>
);}}导出默认应用程序;
这里要注意三件事
变量应该前缀
REACT_APP_
例如:
REACT_APP_WEBSITE_NAME=hello
您需要重启服务器以反映更改.
确保您的 root 文件夹中有 .env 文件(与 package.json 相同的位置),而不是 src 文件夹中.
之后你可以像这样访问变量process.env.REACT_APP_SOME_VARIABLE
其他提示
- 无需将变量值用单引号或双引号括起来.
- 不要在每行末尾添加分号
;
或逗号,
.
I am building a react app and i need to fetch data from my api, now i want to store the api url as an environment variable. I have my .env file, i have dotenv installed, here is my code process.env.API_URL is returning undefined.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Home from '../src/components/Home'
import dotenv from 'dotenv'
import path from 'path'
class App extends Component {
render() {
console.log(process.env.API_URL)
return (
<div>
<Home/>
</div>
);
}
}
export default App;
Three things to note here
the variable should be prefixed with
REACT_APP_
eg:
REACT_APP_WEBSITE_NAME=hello
You need to restart the server to reflect the changes.
Make sure you have the .env file in your root folder(same place where you have your package.json) and NOT in your src folder.
After that you can access the variable like this process.env.REACT_APP_SOME_VARIABLE
Additional tips
- No need to wrap your variable value in single or double quotes.
- Do not put semicolon
;
or comma,
at the end of each line.
Read more here and the official docs
这篇关于反应环境变量 .env 返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!