Nextjs使用带有动态变量名的process.env



我在Nextjs中有一个Web应用程序,在服务器和客户端模式下,访问process.env总是会返回我"未定义":

.env文件

NEXT_PUBLIC_CURRENCY_ES=Euros
NEXT_PUBLIC_CURRENCY_MX=Pesos
NEXT_PUBLIC_CURRENCY_GB=Pounds
CURRENCY_ES=Euros
CURRENCY_MX=Pesos
CURRENCY_GB=Pounds

代码:

//Client side 
//country can be: ES, MX, GB
const varName = "NEXT_PUBLIC_CURRENCY_" + country.toUpperCase();
console.log(process.env[varName]); // this returns undefined
console.log(process.env.NEXT_PUBLIC_CURRENCY_ES); // this prints "Euros"

//Server side 
//country can be: ES, MX, GB
const varName = "CURRENCY_" + country.toUpperCase();
console.log(process.env[varName]); // this returns undefined
console.log(process.env.CURRENCY_ES); // this prints "Euros"

如何获取具有有效值的process.env[varName]?没有定义?varName必须是一个变量。谢谢

您不能像以前那样动态访问这些属性,因为Next.js使用webpack的DefinePlugin来"字符串替换";他们

为什么要使用env变量作为货币,它们取决于应用程序运行的env吗?如果没有,只使用常规的POJO(Plain Old Javascript Object(作为可以从所有地方导入的常量。

// currencies.js
export const currencies = {
es: 'Euros',
mx: 'Pesos',
gb: 'Pounds',
};
// otherModule.js
import { currencies } from './path-to/currencies.js';
console.log(currencies.es); // will print "Euros"

使用CCD_ 1变量的最佳实践是用于";config";或依赖于env的值,例如path/accessKey/tokens。

最新更新