sindresorhus / got

🌐 Human-friendly and powerful HTTP request library for Node.js
MIT License
14.27k stars 935 forks source link

Import with typescript (TS1479) #2206

Closed alexey-sh closed 1 year ago

alexey-sh commented 1 year ago

Describe the bug

Unable to import.

Actual behavior

Getting error with npx tsc

 error TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("got")' call instead.
  To convert this file to an ECMAScript module, change its file extension to '.mts', or add the field `"type": "module"` to '/Users/alexeysh/dev/trash/got-ts/package.json'.

Expected behavior

no errors, like on got v11.8.6

Code to reproduce

// src/index.ts
import got from "got";

package.json

{
  "name": "got-ts",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "npx tsc",
    "run": "node --enable-source-maps dist/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "got": "^12.5.3"
  },
  "devDependencies": {
    "typescript": "^4.9.4"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "lib": [
      "ES2022"
    ],
    "module": "node16",
    "target": "ES2022",
    "moduleResolution": "node16",
    "outDir": "dist",
    "skipLibCheck": true
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

I tried different target, module, lib but no luck. The code below works with got v11.8.6.

Checklist

sindresorhus commented 1 year ago

The error says it all. You need the type field in package.json

https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c

winstxnhdw commented 1 year ago

You can just set moduleResolution to Bundler now in TypeScript 5.0

"moduleResolution": "Bundler"

Extension types are ugly.