NextJS中环境变量的动态访问不起作用 [英] Dynamic access of environment variables in NextJS not working

查看:73
本文介绍了NextJS中环境变量的动态访问不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在 NextJS 中动态访问环境变量.在 .env.local 我有:

I cannot access environment variables dynamically in NextJS. In .env.local I have:

NEXT_PUBLIC_TEST=test

_app.tsx 我有:

const test = "NEXT_PUBLIC_TEST";
console.log(process.env.NEXT_PUBLIC_TEST); // = 'test'
console.log(process.env[test]); // = undefined

我在 Create React APP 中尝试过同样的事情:

I tried the same thing in Create React APP:

# .env
const test = 'REACT_APP_TEST'
console.log(process.env.REACT_APP_TEST) // = 'test'
console.log(process.env[test]) // = 'test'

有人知道为什么 NextJS 不允许这样做以及如何覆盖它吗?我知道 next.config.js 是一个东西,但我想使用 .env.

Does anybody know why NextJS doesn't allow this and how to override it? I'm aware next.config.js is a thing, but I'd like to use .env.

推荐答案

根据官方文档:

注意:为了保证仅服务器机密的安全,Next.js 在构建时将 process.env.* 替换为正确的值.这意味着 process.env 不是标准的 JavaScript 对象.

Note: In order to keep server-only secrets safe, Next.js replaces process.env.* with the correct values at build time. This means that process.env is not a standard JavaScript object.

因此,您尝试做的事情只能在开发模式下进行,在服务器端代码中也是如此.

Hence what you are trying to do is only possible in development mode, that too in the server side code.

如果您真的想使用动态值,您可以手动创建一个映射公开环境常量的对象并使用它来代替 process.env.

You can manually create an object that maps exposed environment constants and use it instead of process.env if you truly want to use dynamic values.

这里是一个例子:

// utils/config.js

export default {
  TEST: process.env.NEXT_PUBLIC_TEST
};

// pages/index.js

import config from "../utils/config";

const test = "TEST";
console.log(config[test]);

const IndexPage = () => <div>Hello World</div>;
export default IndexPage;

这篇关于NextJS中环境变量的动态访问不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆