Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript cannot find module 'worker_threads'

I am trying to use node.js 'worker_threads' library with Node v14.15.1 and getting this error

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.

my code -

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

worker threads got stable after node 11. So it should work. What am i doing wrong ?

PS - I ran same code with JS and it worked fine so i don't think its Node.js issue. Other core libraries like fs are also working fine. Do I need any additional config for TS ?

like image 365
Rohan Gulati Avatar asked Dec 19 '20 15:12

Rohan Gulati


Video Answer


2 Answers

This issue was that I was using quite old versions. After updating, the issue was resolved. If someone faces same issue, update these versions in your package.json - I have updated to

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

Also make sure Nodejs version is 12 LTS or above to have stable 'worker-thread' support.

like image 121
Rohan Gulati Avatar answered Oct 07 '22 21:10

Rohan Gulati


In my case, this problem happened in my Angular project after npm audit fix --force

So after few attempts here's what I did:

  • updating node with sudo n stable (you should install Node’s version manager first)

  • ng update

This command will give you few recommendations in a column named Command to update run each separately and make sure it worked correctly.

Then I run ng serve and everything got back to normal.

like image 40
Vala Khosravi Avatar answered Oct 07 '22 19:10

Vala Khosravi