【发布时间】:2021-12-25 14:21:59
【问题描述】:
我正在尝试将包 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"
]
}
节点版本:v14.18.0
【问题讨论】:
-
在您的 tsconfig 中,您的模块为 commonjs。试试
"module": "es2017", -
当我这样做时,我还必须删除
"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? -
请添加重现错误的minimal reproducible example
标签: node.js typescript es6-modules