反应环境变量 .env 返回未定义 [英] react evironment variables .env return undefined

查看:65
本文介绍了反应环境变量 .env 返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 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><主页/>

);}}导出默认应用程序;

解决方案

这里要注意三件事

  1. 变量应该前缀REACT_APP_

    例如:REACT_APP_WEBSITE_NAME=hello

  2. 您需要重启服务器以反映更改.

  3. 确保您的 root 文件夹中有 .env 文件(与 package.json 相同的位置),而不是 src 文件夹中.

之后你可以像这样访问变量process.env.REACT_APP_SOME_VARIABLE

其他提示

  1. 无需将变量值用单引号或双引号括起来.
  2. 不要在每行末尾添加分号 ; 或逗号 ,.

阅读更多此处和官方docs

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

  1. the variable should be prefixed with REACT_APP_

    eg: REACT_APP_WEBSITE_NAME=hello

  2. You need to restart the server to reflect the changes.

  3. 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

  1. No need to wrap your variable value in single or double quotes.
  2. Do not put semicolon ; or comma , at the end of each line.

Read more here and the official docs

这篇关于反应环境变量 .env 返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆