From 311026f0eb327874ca43e3ecccb9a9916f0850fb Mon Sep 17 00:00:00 2001 From: Andreas Girgensohn Date: Mon, 6 Sep 2021 09:12:29 -0700 Subject: [PATCH] fix: check for Blob before creating worker URL, close #4462 (#4674) --- packages/playground/worker/__tests__/worker.spec.ts | 1 + packages/vite/src/node/plugins/worker.ts | 11 +++++------ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/playground/worker/__tests__/worker.spec.ts b/packages/playground/worker/__tests__/worker.spec.ts index eb5eb2a35f0c7b..93bc590cb90b4e 100644 --- a/packages/playground/worker/__tests__/worker.spec.ts +++ b/packages/playground/worker/__tests__/worker.spec.ts @@ -65,5 +65,6 @@ if (isBuild) { expect(content).toMatch(`new SharedWorker("/assets`) // inlined expect(content).toMatch(`(window.URL||window.webkitURL).createObjectURL`) + expect(content).toMatch(`window.Blob`) }) } diff --git a/packages/vite/src/node/plugins/worker.ts b/packages/vite/src/node/plugins/worker.ts index ca54617d55a04d..35f6f338523222 100644 --- a/packages/vite/src/node/plugins/worker.ts +++ b/packages/vite/src/node/plugins/worker.ts @@ -75,15 +75,14 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin { const content = Buffer.from(code) if (query.inline != null) { // inline as blob data url - return `const blob = new Blob([atob(\"${content.toString( - 'base64' - )}\")], { type: 'text/javascript;charset=utf-8' }); + return `const encodedJs = "${content.toString('base64')}"; + const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" }); export default function WorkerWrapper() { - const objURL = (window.URL || window.webkitURL).createObjectURL(blob); + const objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob); try { - return new Worker(objURL); + return objURL ? new Worker(objURL) : new Worker("data:application/javascript;base64," + encodedJs, {type: "module"}); } finally { - (window.URL || window.webkitURL).revokeObjectURL(objURL); + objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL); } }` } else {