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
ts-node supports a variety of options which can be specified via tsconfig.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With