如何在 TypeScript 项目中导入 Node 模块。ERR_REQUIRE_ESM。

14

我想在我的TypeScript项目中导入p-limit包。当我尝试使用tsc && node serve.js运行项目时,出现以下错误。

我已经被卡了几个小时了...

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.

这份代码在 file.ts 中引起了问题:

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版本:v14.18.0


1
在你的 tsconfig 中,你的模块是 commonjs。尝试使用 "module": "es2017" - gaitat
当我这样做时,我还必须删除"resolveJsonModule": true,因为它们是冲突的。在那之后,在构建时,我会收到像这样的错误:node_modules/@types/mongodb/index.d.ts:46:78 - error TS2792: Cannot find module 'bson'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option? - Joel'-'
请添加一个最小可复现示例,以重现错误。 - gaitat
2个回答

15

6
这不是一个有效的答案,也没有回答问题。 - ArrH
@ArrH 为什么不呢?对我来说似乎非常准确,我正好在寻找完全相同的东西。 - Nathan H
这是一个针对特定问题的解决方法,但并不适用于问题的标题。 - undefined

-5

添加

"lib": [
    "es2017"
]

回到你的tsconfig.json


2
遗憾的是,仍然和我最初发布时一模一样的错误。 - Joel'-'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接