【问题标题】:Nextjs using process.env with dynamic variable nameNextjs 使用带有动态变量名的 process.env
【发布时间】:2023-03-14 08:49:02
【问题描述】:

我在 Nextjs 中有一个服务器和客户端模式的 webapp,像这样访问 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 必须是一个变量。 谢谢!

【问题讨论】:

    标签: node.js webpack next.js


    【解决方案1】:

    您不能像以前那样动态访问这些属性,因为 Next.js 使用 webpack's DefinePlugin 来“字符串替换”它们。

    您为什么使用环境变量来表示货币,它们是否取决于应用程序运行的环境?如果不是,则仅使用常规 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"
    

    使用env 变量的最佳做法是用于“配置”或环境相关值的变量,例如路径/accessKey/令牌。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-01
      • 2016-02-04
      • 2019-02-03
      • 2021-12-04
      • 1970-01-01
      • 2012-03-04
      相关资源
      最近更新 更多