introduction
通常你想要使用构建时环境变量去提供自己的配置,对此的原因是运行时配置增加了渲染 / 初始化消耗并且和自动静态优化不兼容 …
为了增加运行时配置到你的应用种(打开next.config.js并增加publicRuntimeConfig以及 serverRuntimeConfig 配置)
module.exports = {serverRuntimeConfig: {// Will only be available on the server sidemySecret: 'secret',secondSecret: process.env.SECOND_SECRET, // Pass through env variables},publicRuntimeConfig: {// Will be available on both server and clientstaticFolder: '/static',},}
在serverRuntimeConfig中放置任何仅服务端运行时配置 ..
对于publicRuntimeConfig中的配置能够同时在客户端和服务端代码中访问 …
依赖于publicRuntimeConfig的页面必须使用getInitialProps或者getServerSideProps或者你的应用必须存在使用getIntialProps的自定义App ..去取消自动静态优化 …
运行时配置对于没有任何服务端渲染的页面或者页面中的组件不可用 …
(因为它是运行时配置) …
为了在app中访问运行时配置,你可以使用next/config,类似于
import getConfig from 'next/config'import Image from 'next/image'// Only holds serverRuntimeConfig and publicRuntimeConfigconst { serverRuntimeConfig, publicRuntimeConfig } = getConfig()// Will only be available on the server-sideconsole.log(serverRuntimeConfig.mySecret)// Will be available on both server-side and client-sideconsole.log(publicRuntimeConfig.staticFolder)function MyImage() {return (<div><Imagesrc={`${publicRuntimeConfig.staticFolder}/logo.png`}alt="logo"layout="fill"/></div>)}export default MyImage
