Ale*_*leG 1 client-side environment-variables nextjs
在我们的实施过程中,我们创建了一个单一的建筑,并经历了不同的阶段(集成、分期和生产)。在每种环境中,我们都有不同的环境差异。
问题在于,当我们启动服务器时,它只引用了服务器上的环境变量,而在客户端中 process.env 文件是空的。
堆栈:“下一个”:“5.0.0”“babel-plugin-inline-dotenv”:“1.1.1”,
加载 .env 文件使用“inline-dotenv”
小智 6
您可以publicRuntimeConfig在 next.config.js 文件中使用。
例子:
// 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
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,publicRuntimeConfig.mySecret现在是从环境变量中获取的值。所以现在您可以通过 importin 读取该值next/config
例子:
import getConfig from 'next/config';
const { publicRuntimeConfig } = getConfig();
console.log(publicRuntimeConfig.mySecret);
Run Code Online (Sandbox Code Playgroud)
来源:next.js 文档