Skip to content

Commit

Permalink
fix: try catch createObjectURL fail
Browse files Browse the repository at this point in the history
  • Loading branch information
fi3ework committed Mar 14, 2023
1 parent 6243ddd commit bede82c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
18 changes: 14 additions & 4 deletions packages/vite/src/node/plugins/worker.ts
Expand Up @@ -299,11 +299,21 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
const blobCode = `${encodedJs}
const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
export default function WorkerWrapper() {
const objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
let objURL;
let tryBase64 = true;
try {
return objURL ? new ${workerConstructor}(objURL) : new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
} finally {
objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
if(objURL) {
const worker = new ${workerConstructor}(objURL);
tryBase64 = false;
return worker;
}
} catch(e) {
objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
} finally {
if(tryBase64) {
return new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
}
}
}`

Expand All @@ -314,7 +324,7 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
`

return {
// SharedWorker does not support blob URL
// Using blob URL for SharedWorker results in multiple instances of a same worker
code: workerConstructor === 'Worker' ? blobCode : base64Code,
// Empty sourcemap to suppress Rollup warning
map: { mappings: '' },
Expand Down
2 changes: 1 addition & 1 deletion playground/worker/__tests__/es/es-worker.spec.ts
Expand Up @@ -80,7 +80,7 @@ describe.runIf(isBuild)('build', () => {
expect(content).toMatch(`(window.URL||window.webkitURL).createObjectURL`)
expect(content).toMatch(`window.Blob`)
expect(content).toMatch(
/try\{return .*\?new Worker\(.+\):new Worker\("data:application\/javascript;base64,"\+/,
/try\{if\(\w+=\w+&&\(window\.URL\|\|window\.webkitURL\)\.createObjectURL\(\w+\),\w+\{const \w+=new Worker\(\w+\);/,
)
// inlined shared worker
expect(content).toMatch(
Expand Down

0 comments on commit bede82c

Please sign in to comment.