Webpack 5的Bundle Worker,不启动Worker



我想用Webpack 5捆绑一个WebWorker脚本。给定当前文档,执行此操作的方法是:

const worker = new Worker('./path_to_worker.js', import.meta.url)

然而,我想在定义它的不同上下文中启动worker。我想获得工作线程的url字符串,并在其他地方启动它。

const workerUrl = ... get webpack bundled path to worker...

... somewhere else in the code ...
let worker = new Worker(workerUrl)

动态导入可以为Worker生成bundle,但是我无法获得导入脚本的url,所以我可以在程序执行的稍后时刻将它传递给Worker构造函数。

我怎么能做到这一点?

这是目前我能想到的最好的hack:

function getWorkerUrl() {
class FakeWorker {
constructor(url: string | URL) {}
}
let oldWorker = self.Worker
// override the default Worker class temporarily to prevent the worker from launching
//@ts-ignore
self.Worker = FakeWorker
// this will generate the worker bundle with a specified name 
let worker = new Worker(new URL("./worker.ts" /* webpackChunkName: 'bundle-worker.js' */, import.meta.url))
// determine the path to the bundle
const url = './path_to_js/bundle-worker.js'
// restore the original Worker api
self.Worker = oldWorker
return url
}

最新更新