Skip to content

Commit

Permalink
fix: separate blob and base64 code
Browse files Browse the repository at this point in the history
  • Loading branch information
fi3ework committed Mar 8, 2023
1 parent d3fb5f7 commit b111ee7
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 16 deletions.
36 changes: 21 additions & 15 deletions packages/vite/src/node/plugins/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,23 +278,29 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
getDepsOptimizer(config, ssr)?.registerWorkersSource(id)
if (query.inline != null) {
const chunk = await bundleWorkerEntry(config, id, query)
const encodedJs = `const encodedJs = "${Buffer.from(
chunk.code,
).toString('base64')}";`
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);
try {
return objURL ? new ${workerConstructor}(objURL) : new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
} finally {
objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
}
}`

const base64Code = `${encodedJs}
export default function WorkerWrapper() {
return new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
}
`

// inline as blob data url
return {
code: `const encodedJs = "${Buffer.from(chunk.code).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 = blob && (window.URL || window.webkitURL).createObjectURL(blob);
try {
return objURL && ${
inlineUrl === 'blob'
} ? new ${workerConstructor}(objURL) : new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
} finally {
objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
}
}`,

code: inlineUrl === 'blob' ? blobCode : base64Code,
// Empty sourcemap to suppress Rollup warning
map: { mappings: '' },
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ describe.runIf(isBuild)('build', () => {

// inlined
expect(content).toMatch(
`;try{return new Worker("data:application/javascript;base64,"+`,
`return new Worker("data:application/javascript;base64,"+`,
)
})
})

0 comments on commit b111ee7

Please sign in to comment.