【问题标题】:How to only read Google maps API key in production如何在生产中仅读取 Google 地图 API 密钥
【发布时间】: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}}

先谢谢了!

请询问我是否说清楚了。

【问题讨论】:

标签: javascript reactjs google-maps ecmascript-6


【解决方案1】:

如果你使用 Create React App,你可以使用process.env.NODE_ENV。 它会自动设置为developmentproduction

https://create-react-app.dev/docs/adding-custom-environment-variables

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 2016-01-08
    相关资源
    最近更新 更多