如何在ts节点上使用WebWorker? (没有webpack)

时间:2018-10-23 18:02:04

标签: node.js typescript web-worker ts-node

是否可以在不使用webpack的情况下将ts-node与WebWorkers一起使用??

当我这样做时:

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

我得到:

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

有什么想法吗?

Tomer

1 个答案:

答案 0 :(得分:1)

您可以使用WorkerOption参数的eval属性来制作魔术功能。

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
    );
}

因此您可以创建如下线程:

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

希望它可以提供帮助。