尝试在 create-react-app 中使用 dotenv 时出现“未捕获的引用错误:进程未定义”

Kur*_*eek 5 javascript environment-variables reactjs

在存储库https://github.com/khpeek/trailmaps中,我有一个创建的 Google 地图示例,react-google-maps其中googleMapUrlprop 包含我的 Google 地图 API 密钥。根据 12 因素原则,我想将此 API 密钥移至.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;
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

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

Clo*_*tha 6

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

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

为变量添加前缀REACT_APP_应该可以按预期工作。