打字稿找不到模块“worker_threads”

时间:2020-12-19 15:39:15

标签: node.js typescript node-worker-threads

我正在尝试在 Node v14.15.1 中使用 node.js 'worker_threads' 库并收到此错误

Cannot find module 'worker_threads' or its corresponding type declarations.ts(2307)
tsc 

src/api/services/email.service.ts:1:62 - error TS2307: Cannot find module 'worker_threads'.

1 import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';
                                                              

Found 1 error.

我的代码 -

import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';

工作线程在节点 11 之后变得稳定。所以它应该可以工作。 我做错了什么?

PS - 我用 JS 运行了相同的代码,它运行良好,所以我不认为它的 Node.js 问题。其他核心库如 fs 也工作正常。我需要为 TS 做任何额外的配置吗?

3 个答案:

答案 0 :(得分:2)

就我而言,这个问题发生在我的 Angular 项目中 npm audit fix --force

之后

所以经过几次尝试后,我做到了:

  • 使用 sudo n stable 更新节点(您应该先安装 Node 的版本管理器)

  • ng update

此命令将在名为更新命令的列中为您提供一些建议,分别运行每个命令并确保其正常工作。

然后我运行 ng serve,一切都恢复正常。

答案 1 :(得分:1)

将此 package.json 文件与您的 ts 文件一起用作 index.ts 问题将得到解决

{
  "name": "threads-worshop",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start:build": "tsc -w",
    "start:run": "nodemon build/index.js",
    "start": "concurrently npm:start:*"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/node": "^14.14.10",
    "concurrently": "^5.3.0",
    "nodemon": "^2.0.6"
  }
}

在 macOS bigSur 11.0.1 上品尝

答案 2 :(得分:1)

这个问题是我使用的版本很旧。更新后,问题得到解决。 如果有人面临同样的问题,请在您的 package.json 中更新这些版本 - 我已经更新到

  • "@types/node": "14.14.14"
  • "ts-node": "9.1.1"

还要确保 Nodejs 版本为 12 LTS 或更高版本,以获得稳定的“工作线程”支持。