我正在嘗試在 NextJs 中實作網路作業者,我已經遵循了他們的例子,但它真的讓我感到困擾,我無法將作業者相對 URL 作為變數傳遞給new URL(url, baseUrl).
以下代碼段是呼叫 worker 的地方:
import { useEffect, useRef, useCallback } from 'react'
export default function Index() {
const workerRef = useRef()
useEffect(() => {
const workerUrl = '../worker.js';
console.log({
URL: new URL('../worker.js', import.meta.url),
meta: import.meta.url
});
console.log({
URL: new URL(workerUrl, import.meta.url),
meta: import.meta.url
});
workerRef.current = new Worker(new URL('../worker.js', import.meta.url))
workerRef.current.onmessage = (evt) =>
alert(`WebWorker Response => ${evt.data}`)
return () => {
workerRef.current.terminate()
}
}, [])
const handleWork = useCallback(async () => {
workerRef.current.postMessage(100000)
}, [])
return (
<div>
<p>Do work in a WebWorker!</p>
<button onClick={handleWork}>Calculate PI</button>
</div>
)
}
這奇怪地記錄:
{
"URL":"/_next/static/media/worker.3c527896.js",
"meta":"file:///home/omar/CODE/NextJs/lullo/with-web-worker-app/pages/index.js"
}
{
"URL":"file:///home/omar/CODE/NextJs/lullo/with-web-worker-app/worker.js",
"meta":"file:///home/omar/CODE/NextJs/lullo/with-web-worker-app/pages/index.js"
}
這到底有什么不同:
const workerUrl = '../worker.js';
console.log({
URL: new URL('../worker.js', import.meta.url),
meta: import.meta.url
});
console.log({
URL: new URL(workerUrl, import.meta.url),
meta: import.meta.url
});
問題是我無法將 URL 作為道具傳遞給一些通用的工人呼叫者。我收到煩人的錯誤:
SecurityError: Failed to construct 'Worker': Script at 'file:///home/omar/CODE/NextJs/lullo/client/src/utils/WebWorkers/postErrorToServer.ts' cannot be accessed from origin 'http://localhost:3000'.
uj5u.com熱心網友回復:
這可能會發生,因為在第一種情況下:
const workerUrl = '../worker.js';
const url = new URL(workerUrl, import.meta.url);
webpack 將 URL 視為動態的,并且無法在編譯時正確捆綁 web worker。如果您按如下方式定義作業人員,則會發生類似的情況:
const url = new URL('../worker.js', import.meta.url);
const worker = new Worker(url);
對 webpack 的 GitHub 存盤庫中的討論的此評論可能對您的情況有所幫助。由于上述原因,我不認為作業 URL 可以是真正動態的 - webpack 需要在編譯時知道作業腳本的 URL。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/375535.html
下一篇:查詢資料庫以獲取名字或姓氏
