ran*_*its 5 configuration reactjs next.js
我正在查看next.js文档并尝试了解建议的方法用于设置在不同环境中更改的 URL。大多数情况下,我想确保在开发和生产中正确指向后端 URL。
我想您可以创建一个常量配置文件,但是是否有支持的最佳实践?
您可以使用配置您的下一个应用程序,它允许您使用下一个运行时next-runtime-dotenv配置指定serverOnly / clientOnly值。
然后在某个组件中
\n\nimport getConfig from \'next/config\'\n\nconst {\n publicRuntimeConfig: {MY_API_URL}, // Available both client and server side\n serverRuntimeConfig: {GITHUB_TOKEN} // Only available server side\n} = getConfig()\n\nfunction HomePage() {\n // Will display the variable on the server\xe2\x80\x99s console\n // Will display undefined into the browser\xe2\x80\x99s console\n console.log(GITHUB_TOKEN)\n\n return (\n <div>\n My API URL is {MY_API_URL}\n </div>\n )\n}\n\nexport default HomePage\nRun Code Online (Sandbox Code Playgroud)\n\n如果您不需要这种分离,您可以使用dotenvlib 加载您的.env文件,并用它配置 Next 的env属性。
// next.config.js\n\nrequire(\'dotenv\').config()\nmodule.exports = {\n env: {\n // Reference a variable that was defined in the .env file and make it available at Build Time\n TEST_VAR: process.env.TEST_VAR,\n },\n}\nRun Code Online (Sandbox Code Playgroud)\n\n检查这个with-dotenv示例。
\n| 归档时间: |
|
| 查看次数: |
11802 次 |
| 最近记录: |