简体   繁体   中英

Worker threads with ts-node

I am planning to have worker threads for socket.io rooms. I create a worker thread on the first connection to a room which then sets up firebase listeners.

Unfortunately. I have common imports in the worker file and my main source code.

I followed this article to allow running ts files via worker_threads -> https://wanago.io/2019/05/06/node.js-typescript-12-worker-threads/

Unfortunately, I dont get top-level await and upon starting the worker thread, I get the following error. error TS2451: Cannot redeclare block-scoped variable 'tslib_1'.\r\n"

Here is my tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "lib": ["esnext"],
    "module": "commonjs",
    "importHelpers": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "node",
    "baseUrl": ".",
    "sourceMap": true,
    "declaration": false,
    "noImplicitAny": false,
  },
  "files": [
    "typings.d.ts"
  ],
}

You haven't provided any info on how you run your application, so I will suppose the following setup:

  • you run your main application by requiring ts-node on command line:

     node -r ts-node/register index.ts
  • your worker entry point is a .ts file, you instantiate it as follows:

     new Worker('./worker.ts')
  • you have the following code near the top of your worker script:

     require('ts-node').register();

Assuming this is your setup, you need to remove the line

require('ts-node').register();

from your worker entry point script. This line is basically causing your TypeScript file to be compiled twice by ts-node , hence the double declaration error for tslib_1 .

Registering ts-node manually like above is only necessary, when your main program wan't started with the -r ts-node/register flag. If it was, then ts-node will be automatically required when you instantiate your worker and will compile the requested TS sources on-the-fly.

There are a few other gotchas that you have to keep in mind when using workers:

  • The new Worker(...) API resolves the requested file relatively to your working directory, if you want to resolve relatively to the current souce file you'll need to do something like this: new Worker(path.resolve(__dirname, './worker.ts')) .
  • If you don't use ts-node in production and instead compile your sources via tsc , you won't be able to load the worker script after your sources are compiled to JS, your worker file will become worker.js (mind the file extension). You'll need to detect this situation and change the path accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM