NextJS - 在应用程序启动时设置动态环境变量 [英] NextJS - Set dynamic environment variables at the start of the application
问题描述
在我们的实施过程中,我们创建了一个单独的建筑,并经历了不同的阶段(集成、登台和生产).在每种环境中,我们都有不同的环境差异.
In our implementation process we created a single building and went through the different stages (integration, staging and production). In each of the environments, we have variable environmental differences.
问题是,当我们启动服务器时,它只引用服务器上的环境变量,但在客户端,process.env 文件是空的.
The problem is that when we started the server it only referred to the environment variables on the server, but in the client the process.env file is empty.
堆栈:下一个":5.0.0"babel-plugin-inline-dotenv":1.1.1",
stack: "next": "5.0.0" "babel-plugin-inline-dotenv": "1.1.1",
用于加载 .env 文件使用inline-dotenv"
for load .env file is used "inline-dotenv"
推荐答案
您可以在 next.config.js 文件中使用 publicRuntimeConfig
.
You can use publicRuntimeConfig
in your next.config.js file.
例子:
// next.config.js
module.exports = {
serverRuntimeConfig: { // Will only be available on the server side
mySecret: 'secret'
},
publicRuntimeConfig: { // Will be available on both server and client
staticFolder: '/static',
mySecret: process.env.MY_SECRET // Pass through env variables
}
}
请注意,publicRuntimeConfig.mySecret
的值现在是从环境变量中获取的.所以现在您可以通过 importin next/config
note that the value of publicRuntimeConfig.mySecret
is now getting fetched from the environment variables.
So now you can read that value by importin next/config
例子:
import getConfig from 'next/config';
const { publicRuntimeConfig } = getConfig();
console.log(publicRuntimeConfig.mySecret);
来源:next.js 文档
这篇关于NextJS - 在应用程序启动时设置动态环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!