简体   繁体   中英

Using top level fetch in typescript

I am a bit confused. The idea is to write write ES2022 in order to use top level await and fetch , to use in NodeJS only.

Following the compiler advice:

src/index.ts:48:3 - error TS1378: Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher.

I have set the module to es2022, and the target to es2020 (which is enough in my case.)

I want the target to be ES2020 so that older versions of node would run the code.

According to TS there shouldn't ea problem with this (see config at the bottom)

Yet once compiled I get the error that

await fetch(...)

ReferenceError: fetch is not defined

This is my tsconfig:

{
  "compilerOptions": {
    "outDir": "lib-esm",
    "esModuleInterop": true,
    "moduleResolution": "node",
    "module": "es2022",
    "target": "es2020"
  },
  "include": ["./src/**/*"],
}

Why would it be so? Any help?

Silly error, I just had to change nvm to node version 19 (that supports fetch):

nvm use 19

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM