在我们的实施过程中,我们创建了一座建筑并经历了不同的阶段(集成、分期和生产)。在每种环境中,我们都有不同的环境差异。
问题在于,当我们启动服务器时,它只引用了服务器上的环境变量,但在客户端中,process.env 文件是空的。
堆栈:“下一个”:“5.0.0”“babel-plugin-inline-dotenv”:“1.1.1”,
加载 .env 文件使用“inline-dotenv”
您可以在 next.config.js 文件中使用
publicRuntimeConfig
。
示例:
// 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
示例:
import getConfig from 'next/config';
const { publicRuntimeConfig } = getConfig();
console.log(publicRuntimeConfig.mySecret);
来源:next.js 文档
我为此付出了很多努力,因为我无力为每个环境(例如 qa、阶段、生产等)构建 docker 镜像。因此,我创建了以下 npm 包。请检查一下,也许它会为某人节省很多时间:next-config-env-variables-patch