需要 dotenv 时如何修复 'require(...).config(...) is not a function' 错误

How to fix 'require(...).config(...) is not a function' error when requiring dotenv

我在使用 dotenv 时遇到此错误:

(async () => {
^
TypeError: require(...).config(...) is not a function

一切正常,直到我需要 dotenv。

这是代码

const puppeteer = require('puppeteer');
const fs = require('fs');
require('dotenv').config()

(async () => {
  const browser = await puppeteer.launch({
    headless: false,
    args: ['--start-maximized'],
    defaultViewport: null,
  });

  const page = await browser.newPage();
  ...more code here
})()

Dotenv 已正确安装:

  "dependencies": {
    "dotenv": "^8.2.0",
    "puppeteer": "^5.3.1"
  }

您似乎只是漏掉了这一行之后的分号:

require('dotenv').config()

因此解析器将下一行的括号解析为函数调用。