webpack 5 web worker support for CORS? #14648
Answered
by
piotr-oles
piotr-oles
asked this question in
Q&A
-
Hi! I would like to use the new worker import syntax: const worker = new Worker(new URL('./worker', import.meta.url)); to share code between the main thread and the worker. Unfortunately, the project I'm working on uses CDN on a separate domain, and I get CORS error. Would it be possible to add some option in webpack configuration or somewhere else to use work-around with From:const worker = new Worker(new URL('./worker', import.meta.url)); To:const objectURL = URL.createObjectURL(
new Blob([`importScripts(${JSON.stringify(generatedUrlToWorker)});`], { type: 'application/javascript' })
);
const worker = new Worker(objectURL);
URL.revokeObjectURL(objectURL); |
Beta Was this translation helpful? Give feedback.
Answered by
piotr-oles
Nov 4, 2021
Replies: 3 comments 46 replies
-
I think I found a nice work-around. I created custom worker class in a separate file: export class CorsWorker {
private readonly worker: Worker;
constructor(url: string | URL) {
const objectURL = URL.createObjectURL(
new Blob([`importScripts(${JSON.stringify(url.toString())});`], {
type: 'application/javascript'
})
);
this.worker = new Worker(objectURL);
URL.revokeObjectURL(objectURL);
}
getWorker() {
return this.worker;
}
} and then I imported it in another file as Worker: import { CorsWorker as Worker } from './cors-worker';
// aliasing CorsWorker to Worker makes it statically analyzable
const corsWorker = new Worker(new URL('../worker', import.meta.url));
// tada!
const worker = corsWorker.getWorker(); |
Beta Was this translation helpful? Give feedback.
33 replies
Answer selected by
piotr-oles
-
I thinkt above solution not works. |
Beta Was this translation helpful? Give feedback.
6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think I found a nice work-around. I created custom worker class in a separate file:
and then I imported it in another file as Worker: