如何在生产中只读取 Google 映射 API 键
How to only read Google maps API key in production
我正在开发一个使用 Google 地图的 React 应用程序。我一直只在开发模式下工作,现在想在将它推到生产环境时添加 API 键。
我正在加载 Google 地图脚本,就像下面的代码一样,它似乎可以工作,但我只想从我的 .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}}
谢谢!
请问我说清楚没有。
如果您使用的是 Create React App,则可以使用 process.env.NODE_ENV
。
它会自动设置为 development
或 production
。
https://create-react-app.dev/docs/adding-custom-environment-variables
我正在开发一个使用 Google 地图的 React 应用程序。我一直只在开发模式下工作,现在想在将它推到生产环境时添加 API 键。
我正在加载 Google 地图脚本,就像下面的代码一样,它似乎可以工作,但我只想从我的 .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}}
谢谢!
请问我说清楚没有。
如果您使用的是 Create React App,则可以使用 process.env.NODE_ENV
。
它会自动设置为 development
或 production
。
https://create-react-app.dev/docs/adding-custom-environment-variables