【问题标题】:"Uncaught ReferenceError: process is not defined" in attempt to use dotenv in create-react-app“未捕获的 ReferenceError:未定义进程”试图在 create-react-app 中使用 dotenv
【发布时间】:2018-09-03 19:21:49
【问题描述】:

在存储库https://github.com/khpeek/trailmaps 中,我有一个使用react-google-maps 创建的Google Map 示例,其中googleMapUrl 属性包含我的Google Maps API 密钥。按照 12-factor 原则,我想把这个 API key 移动到一个.env 文件中,并插入到 URL 中。

我正在尝试遵循dotenv 模块(与create-react-app 一起提供)的说明,并尝试了以下操作:

import React, { Component } from 'react';
import './App.css';
import MapWithGroundOverlay from './components/groundOverlay';
require('dotenv').config()

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Custom Overlay</h1>
          <h1 className="App-title">{`The API key is ${process.env.GOOGLE_MAPS_API_KEY}`}</h1>

        </header>
        <MapWithGroundOverlay
          googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyBimnrhiugaGSNN8WnsjpzMNJcrH_T60GI&v=3.exp&libraries=geometry,drawing,places"
          loadingElement={<div style={{ height: `100%` }} />}
          containerElement={<div style={{ height: `400px` }} />}
          mapElement={<div style={{ height: `100%` }} />}
        />
      </div>
    );
  }
}

export default App;

在根目录中,我创建了一个.env 文件,我在其中定义了GOOGLE_MAPS_API_KEY。但是,如果我 npm start 应用程序并转到 localhost:3000,我会发现 process 未定义:

根据Uncaught ReferenceError: process is not defined,Node.js代码必须由Node进程运行,而不是浏览器;据推测,这就是我做错了。但是,我发现这个答案有点高级,可以立即应用在这里。显然,dotenv 应该可以与 create-react-app 一起使用,否则它不会与它捆绑在一起,但我应该在这个示例中使用它吗?

【问题讨论】:

    标签: javascript reactjs environment-variables


    【解决方案1】:

    Dotenv 不适用于浏览器运行时。我建议添加库文档中概述的自定义环境变量。

    https://github.com/khpeek/trailmaps#adding-custom-environment-variables

    使用REACT_APP_ 为变量添加前缀应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-05
      • 2022-07-18
      • 2016-05-22
      • 1970-01-01
      • 2017-05-12
      • 2021-04-26
      • 2016-11-12
      相关资源
      最近更新 更多