Skip to main content

env

Next.js 9.4 发布以来,我们现在对 添加环境变量 有了更直观、更符合人机工程学的体验。试一试!

¥Since the release of Next.js 9.4 we now have a more intuitive and ergonomic experience for adding environment variables. Give it a try!

很高兴知道:以这种方式指定的环境变量将始终包含在 JavaScript 包中,在环境变量名称中添加 NEXT_PUBLIC_ 前缀仅在指定它们时有效 通过环境或 .env 文件

¥Good to know: environment variables specified in this way will always be included in the JavaScript bundle, prefixing the environment variable name with NEXT_PUBLIC_ only has an effect when specifying them through the environment or .env files.

要将环境变量添加到 JavaScript 包,请打开 next.config.js 并添加 env 配置:

¥To add environment variables to the JavaScript bundle, open next.config.js and add the env config:

module.exports = {
env: {
customKey: 'my-value',
},
}

现在你可以在代码中访问 process.env.customKey。例如:

¥Now you can access process.env.customKey in your code. For example:

function Page() {
return <h1>The value of customKey is: {process.env.customKey}</h1>
}

export default Page

Next.js 将在构建时用 'my-value' 替换 process.env.customKey。由于 webpack DefinePlugin 的性质,尝试解构 process.env 变量是行不通的。

¥Next.js will replace process.env.customKey with 'my-value' at build time. Trying to destructure process.env variables won't work due to the nature of webpack DefinePlugin.

例如,以下行:

¥For example, the following line:

return <h1>The value of customKey is: {process.env.customKey}</h1>

最终将是:

¥Will end up being:

return <h1>The value of customKey is: {'my-value'}</h1>