執行時期設定 (Runtime Config)
警告 (Warning)
- 此功能已棄用。建議改用環境變數,它也支援讀取執行時期的值。
- 您可以使用
register
函式在伺服器啟動時執行程式碼。- 此功能不適用於 自動靜態優化、輸出檔案追蹤 或 React 伺服器元件。
要在應用程式中新增執行階段設定,請開啟 next.config.js
並新增 publicRuntimeConfig
和 serverRuntimeConfig
設定
next.config.js
module.exports = {
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
staticFolder: '/static',
},
}
將任何僅限伺服器端的執行階段設定放在 serverRuntimeConfig
下。
任何客戶端和伺服器端程式碼皆可存取的設定都應放在 publicRuntimeConfig
下。
依賴
publicRuntimeConfig
的頁面**必須**使用getInitialProps
或getServerSideProps
,或者您的應用程式必須具有帶有getInitialProps
的 自訂應用程式 以停用 自動靜態優化。未經伺服器端渲染的頁面(或頁面中的元件)將無法使用執行階段設定。
要存取應用程式中的執行階段設定,請使用 next/config
,如下所示
import getConfig from 'next/config'
import Image from 'next/image'
// Only holds serverRuntimeConfig and publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
// Will only be available on the server-side
console.log(serverRuntimeConfig.mySecret)
// Will be available on both server-side and client-side
console.log(publicRuntimeConfig.staticFolder)
function MyImage() {
return (
<div>
<Image
src={`${publicRuntimeConfig.staticFolder}/logo.png`}
alt="logo"
layout="fill"
/>
</div>
)
}
export default MyImage
這有幫助嗎?