【发布时间】:2021-06-16 15:15:27
【问题描述】:
我正在开发一个使用 Google 地图的 React 应用程序。我一直只在开发模式下工作,现在我想在将其推送到生产环境时添加 API 密钥。
我正在像下面的代码一样加载谷歌地图脚本,它似乎可以工作,但我只想从我的 .env 中读取并在生产中使用 API 密钥,而不是在我在 http:// 本地开发时localhost:3000/等。有谁知道有没有简单的方法可以做到这一点?
if (!scriptElementExists) {
// Create a new script tag
const scriptElement = createScriptElement(
'google-maps',
`https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_MAPS_KEY}&callback=${googleMapsData.scriptCallbackName}`
);
// Append the script to the document
document.getElementsByTagName('head')[0].appendChild(scriptElement);
}
我的 .env
# Google Maps Api Key
REACT_APP_GOOGLE_MAPS_KEY={{API_KEY}}
先谢谢了!
请询问我是否说清楚了。
【问题讨论】:
-
@Holtwick 在 [link]stackoverflow.com/questions/3162457/… 的最新答案(2020 年)看起来很有用,似乎涵盖了当前最常见的情况。
标签: javascript reactjs google-maps ecmascript-6