【问题标题】:"TypeError: Cannot read property 'config' of undefined" in dotenvdotenv 中的“TypeError:无法读取未定义的属性‘配置’”
【发布时间】:2021-04-17 02:49:37
【问题描述】:

我正在尝试通过 dotenv 模块访问我的 .env 文件,但出现以下错误

dotenv.config();
       ^
TypeError: Cannot read property 'config' of undefined

我在node_modulespackage.json 中安装了dotenv,我的.env 文件位于根文件夹中,我认为所有内容都已正确写入,但由于某种原因无法正常工作。我试过重新安装模块,没有帮助

【问题讨论】:

    标签: node.js typescript dotenv


    【解决方案1】:

    试试下面的

    require('dotenv').config()

    【讨论】:

      【解决方案2】:

      解决此问题的另一种方法是在 Typescript compiler options 中启用 esModuleInterop

      打开tsconfig.json并添加这一行:

      "esModuleInterop": true,
      

      所以你可以像这样导入它:

      import hello from 'hello-world';
      

      【讨论】:

        【解决方案3】:

        试试这个:

         const path = require('path')
         require('dotenv').config({ path: path.resolve(__dirname, '../.env') })
        

        【讨论】:

        • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
        【解决方案4】:

        尝试以下方法:

        require('dotenv').config({path: __dirname + '/.env'})
        

        在打字稿中

        import * as dotenv from 'dotenv'
        dotenv.config({path: __dirname + '/.env'})
        

        【讨论】:

        • 这也不起作用。我实际上是在使用打字稿并使用“import”关键字导入模块,有没有可能问题出在此处?
        • 更新了我的答案。
        • 谢谢!我的问题是导入,从“import dotenv”切换到“import * as dotenv”确实有帮助
        猜你喜欢
        • 2022-07-06
        • 2022-07-12
        • 2019-02-20
        • 2018-12-20
        • 2022-01-05
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多