Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use WebWorker with ts-node? (without webpack)

Is there any way to use ts-node with WebWorkers but without using webpack?

When I do:

const worker = new Worker('path-to/workerFile.ts', { // ... });

I get:

TypeError [ERR_WORKER_UNSUPPORTED_EXTENSION]: The worker script extension must be ".js" or ".mjs". Received ".ts" at new Worker (internal/worker.js:272:15) // ....

Any ideas?

Tomer

like image 762
kutomer Avatar asked Oct 23 '18 18:10

kutomer


People also ask

Does TS-node use Tsconfig?

ts-node supports a variety of options which can be specified via tsconfig.

What is TS-node in package JSON?

TS-Node is a Node. js package that we can use to execute TypeScript files or run TypeScript in a REPL environment. To compile and run TypeScript directly from the command line, we need to install the compiler and ts-node globally.

What is the use of TS-node register?

Use the Node. js CLI with ts-node/register if you want to run normal Node. js scripts such as a test runner like Mocha, but you want to let ts-node compile TypeScript code on the fly when you try to use require to import TypeScript files.


1 Answers

You can make an function to make the magic, using eval property of WorkerOption parameter.

const workerTs = (file: string, wkOpts: WorkerOptions) => {
    wkOpts.eval = true;
    if (!wkOpts.workerData) {
        wkOpts.workerData = {};
    }
    wkOpts.workerData.__filename = file;
    return new Worker(`
            const wk = require('worker_threads');
            require('ts-node').register();
            let file = wk.workerData.__filename;
            delete wk.workerData.__filename;
            require(file);
        `,
        wkOpts
    );
}

so you can create the thread like this:

let wk = workerTs('./file.ts', {});

Hope it can help.

like image 158
Daniel de Andrade Varela Avatar answered Oct 12 '22 05:10

Daniel de Andrade Varela