简体   繁体   中英

“Uncaught ReferenceError: process is not defined” in attempt to use dotenv in create-react-app

In the repository https://github.com/khpeek/trailmaps , I have an example of a Google Map created with react-google-maps in which the googleMapUrl prop contains my Google Maps API key. In accordance with 12-factor principles, I would like to move this API key into a .env file and interpolate it into the URL.

I'm trying to follow the instructions of the dotenv module (which comes together with create-react-app ), and have attempted the following:

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;

In the root directory, I've created a .env file where I define the GOOGLE_MAPS_API_KEY . However, if I npm start the app and go to localhost:3000 , I get that process is undefined:

在此处输入图片说明

According to Uncaught ReferenceError: process is not defined , Node.js code must be run by the Node process, not the browser; presumably, this is what I'm doing wrong. I find that answer a bit high-level to immediately apply here, however. Clearly, dotenv should be usable with create-react-app or it wouldn't be bundled with it, but am I supposed to use it for this example?

Dotenv is not intended for browser runtimes. I would suggest adding custom environment variables outlined in the library's documentation.

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

Prefixing the variable with REACT_APP_ should work as intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM