NextJS - 如何获取运行时环境变量 [英] NextJS - How to get runtime environment variables

查看:74
本文介绍了NextJS - 如何获取运行时环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

菜鸟问题,我很抱歉.

我想知道是否有人知道 NextJS 自托管(例如 docker 或 kubernetes)的推荐部署流程.我只进行一次典型的构建,根据环境发布,同时更改环境变量以匹配环境,但保持图像相同.

I'm wondering if anyone knows the recommended deployment flow for NextJS self-hosted (e.g. docker or kubernetes). I'm doing a typical build once, ship per environment while changing environment variables to match the environment but keeping the image the same.

由于 NextJS 在您使用getInitialProps"时自动退出 SSG;和publicRuntimeConfig",我想知道,将同一映像部署到多个环境的最佳方式是什么(同样,自托管在通用云上,例如 docker run).

Since NextJS auto-opts-out of SSG when you use "getInitialProps" and "publicRuntimeConfig", I'm wondering, what's the best way to deploy the same image to multiple environments (again, self hosted on generic cloud e.g. docker run).

  1. 我是否必须始终烘焙环境变量?所以我必须为每个环境构建一个映像,并且每次更新到 env vars.
  2. 使用 publicRuntimeConfig/getInitialProps 但忘记 SSG 优化,即使我的变量不敏感(例如 GA_TRACKING_ID)
  3. ...还有别的吗?

感谢您的帮助!

推荐答案

你可能想看看 react-env 就是这样做的.

You might want to check out react-env which does just that.

这个想法是 react-env 将为您生成一个带有环境变量的 __ENV.js JS 文件,然后您可以通过窗口或通过 env 在客户端访问该文件 助手,例如:

The idea is that react-env will generate for you an __ENV.js JS file with your environment variables, which you can then access on client side via the window or via the env helper, eg:

<small>
  Works in the browser: <b>{env("CRA")}</b>.
</small>

使用 Docker 时,您可以设置入口点在容器启动时生成所需的 __ENV.js:

When using Docker, you may set an entrypoint that generates the required __ENV.js when the container boots:

ENTRYPOINT yarn react-env --env APP_ENV

这篇关于NextJS - 如何获取运行时环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆