How to import node module in typescript project. ERR_REQUIRE_ESM

Viewed 6878

I am trying to import the package p-limit into my typescript project. When trying to run the project using tsc && node serve.js, I run into the error below.

Im stuck at this for a few hours now...

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /project/node_modules/p-limit/index.js
require() of ES modules is not supported.
require() of /project/node_modules/p-limit/index.js from /project/dist/services/file.ts is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /project/node_modules/p-limit/package.json.

This piece of code in file.ts is causing the issue:

import pLimit from 'p-limit';
const limit = pLimit(1);

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2017",
    "module": "commonjs",
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "rootDir": "src",
    "outDir": "dist",
    "sourceMap": true,
    "experimentalDecorators": true,
    "types": [
      "node",
      "express"
    ],
    "strictNullChecks": true
  },
  "files": [
    "./node_modules/@types/node/index.d.ts",
    "./node_modules/p-limit/index.d.ts"
  ],
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

Node version: v14.18.0

2 Answers

add

"lib": [
    "es2017"
]

to your tsconfig.json

Related