【发布时间】: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