注意不要使用箭头函数哦
cros-worker.ts
const { location } = globalThis;
/** 判断url是否跨域 */
function detectCors(url: string) {
const a = new URL(url, location.href);
return a.origin !== location.origin;
}
const { Worker } = globalThis;
/**
* 这个就是Worker,但是可以跨域
* 实现了Worker的所有接口
* @see https://developer.mozilla.org/zh-CN/docs/Web/API/Worker
* @see https://github.com/webpack/webpack/discussions/14648
*/
const CorsWorker = (function (scriptURL: string | URL, options?: WorkerOptions | undefined) {
let url = typeof scriptURL === 'string' ? scriptURL.toString() : scriptURL.href;
if (detectCors(url)) {
let scripts: string;
if (options?.type === 'module') {
scripts = `import ${JSON.stringify(url)};`;
} else {
scripts = `importScripts(${JSON.stringify(url)});`;
}
url = URL.createObjectURL(
new Blob([scripts], {
type: 'application/javascript',
})
);
}
return new Worker(url, options);
}) as unknown as typeof Worker
export default CorsWorker;
main引入
import CorsWorker from './utils/cros-worker';
globalThis.Worker = CorsWorker;