ReferenceError:导出未在 ES 模块范围中定义

shi*_*dav 7 javascript node.js async-await typescript

我是打字稿的新手,当我编译代码时,它编译正确,但是当我使用节点运行程序时,我收到此错误 ReferenceError: Exports is not Defined in ES modulescope


ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and 'D:\projects\pro8\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///D:/projects/pro8/await.js:40:1
    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
    at async loadESM (node:internal/process/esm_loader:88:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)
Run Code Online (Sandbox Code Playgroud)

打字稿代码

import fetch from "node-fetch";

const baseApi = "https://reqres.in/api/users?page=1";
const userApi = "https://reqres.in/api/user";
interface Employee {
    id: number
    employee_name: string
    employee_salary: number
    employee_age: number
    profile_image: string
}
const fetchAllEmployees = async (url: string): Promise<Employee[]> => {
  const response = await fetch(url);
  const { data }:any = await response.json();
  return data;
};

const fetchEmployee = async (url: string, id: number): Promise<Record<string, string>> => {
  const response = await fetch(`${url}/${id}`);
  const { data }:any = await response.json();
  return data;
};
const generateEmail = (name: string): string => {
  return `${name.split(" ").join(".")}@company.com`;
};

const runAsyncFunctions = async () => {
  try {
    const employees = await fetchAllEmployees(baseApi);
    Promise.all(
      employees.map(async user => {
        const userName = await fetchEmployee(userApi, user.id);
        const emails = generateEmail(userName.name);
        return emails;
      })
    );
  } catch (error) {
    console.log(error);
  }
};
runAsyncFunctions();
Run Code Online (Sandbox Code Playgroud)

包.json

{
  "name": "pro8",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^5.21.0",
    "@typescript-eslint/parser": "^5.21.0",
    "eslint": "^8.14.0",
    "eslint-config-standard": "^17.0.0",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-n": "^15.2.0",
    "eslint-plugin-promise": "^6.0.0"
  },
  "dependencies": {
    "@types/node-fetch": "^2.6.1",
    "node-fetch": "^3.2.4"
  }
}
Run Code Online (Sandbox Code Playgroud)

我试图解决这个错误ts An async function or method in ES5/ES3 require the 'Promise' constructor

任何答案都不适用于我的情况

所以请给我解决方案(如果有)

P S*_*vva 1

"type": "module"尝试从 中删除package.json。我以前遇到过这个问题,它似乎可以解决问题。

  • 你能解释一下我们为什么要这样做吗? (2认同)
  • 这不是一个充分的答案,请解释更多。 (2认同)