如何在打字稿项目中导入节点模块。 ERR_REQUIRE_ESM
How to import node module in typescript project. ERR_REQUIRE_ESM
我正在尝试将包 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
添加
"lib": [
"es2017"
]
给你的tsconfig.json
p-limit 4.0.0 及更高版本现在仅限 ESM。您可以将 p-limit 降级到 3.1.0,这是 commonjs,它应该可以正常工作。
This package is now pure ESM. Please read this.
https://github.com/sindresorhus/p-limit/releases/tag/v4.0.0
或者,您可以将项目从 CJS 切换到 ESM,但这是一个更大的问题。
我正在尝试将包 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
添加
"lib": [
"es2017"
]
给你的tsconfig.json
p-limit 4.0.0 及更高版本现在仅限 ESM。您可以将 p-limit 降级到 3.1.0,这是 commonjs,它应该可以正常工作。
This package is now pure ESM. Please read this.
https://github.com/sindresorhus/p-limit/releases/tag/v4.0.0
或者,您可以将项目从 CJS 切换到 ESM,但这是一个更大的问题。