node.jstypescriptts-nodeworker-thread

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"
  ],
}

Solution

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

    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: