Home > Software engineering >  How to import node module in typescript project. ERR_REQUIRE_ESM
How to import node module in typescript project. ERR_REQUIRE_ESM

Time:11-15

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

CodePudding user response:

add

"lib": [
    "es2017"
]

to your tsconfig.json

CodePudding user response:

p-limit 4.0.0 and above are now ESM only. You can downgrade p-limit to 3.1.0 which is commonjs and it should work fine.

This package is now pure ESM. Please read this.

https://github.com/sindresorhus/p-limit/releases/tag/v4.0.0

Alternatively you can switch your project from CJS to ESM, but that's a larger issue.

https://nodejs.org/api/esm.html

  • Related