Search code examples
node.jstypescriptweb-workerts-node

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


Solution

  • 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.