8

有没有办法将 ts-node 与 WebWorkers 一起使用不使用 webpack?

当我做:

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) // ....

有任何想法吗?

托默

4

1 回答 1

13

您可以使用 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', {});

希望它可以提供帮助。

于 2019-09-16T01:52:53.427 回答