4

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

1 Answer 1

8

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.
1
  • Thanks, your The new Worker(...) API resolves the requested file relatively to your working directory hint is what I was missing! Aug 14, 2023 at 19:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.