From c3f27d9cc8c9e246e2bba9fd16e65bc381374fe3 Mon Sep 17 00:00:00 2001 From: "Yuichiro Tachibana (Tsuchiya)" Date: Thu, 9 Jan 2025 09:32:02 +0900 Subject: [PATCH] Update CrossOriginWorker to work with type=module (#1219) --- packages/kernel/src/cross-origin-worker.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/kernel/src/cross-origin-worker.ts b/packages/kernel/src/cross-origin-worker.ts index 8511c2696..2906688b9 100644 --- a/packages/kernel/src/cross-origin-worker.ts +++ b/packages/kernel/src/cross-origin-worker.ts @@ -10,7 +10,7 @@ const workerBlobUrlCache = new Map(); -function getWorkerBlobUrl(url: URL): string { +function getWorkerBlobUrl(url: URL, isModule = false): string { const urlStr = url.toString(); const cached = workerBlobUrlCache.get(urlStr); @@ -19,8 +19,12 @@ function getWorkerBlobUrl(url: URL): string { return cached; } - const workerBlob = new Blob([`importScripts("${urlStr}");`], { - type: "text/javascript", + const workerCode = isModule + ? `import "${urlStr}";` + : `importScripts("${urlStr}");`; + + const workerBlob = new Blob([workerCode], { + type: isModule ? "text/javascript;type=module" : "text/javascript", }); const workerBlobUrl = URL.createObjectURL(workerBlob); workerBlobUrlCache.set(urlStr, workerBlobUrl); @@ -52,7 +56,10 @@ export class CrossOriginWorkerMaker { // so we can't catch the error synchronously. } else { console.debug(`Loading a worker script from a different origin: ${url}`); - const workerBlobUrl = getWorkerBlobUrl(url); + const workerBlobUrl = getWorkerBlobUrl( + url, + workerOptions.type === "module", + ); this.worker = shared ? new SharedWorker(workerBlobUrl, workerOptions) : new Worker(workerBlobUrl, workerOptions);