Skip to content

Commit

Permalink
Use classic workers in production for the cross origin worker trick o…
Browse files Browse the repository at this point in the history
…n a page loaded via file:// scheme (#1258)

* Use classic workers in production for the cross origin worker trick on a page loaded via file:// scheme

* Fix comment
  • Loading branch information
whitphx authored Jan 11, 2025
1 parent c5ca6bb commit 8956d07
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
4 changes: 4 additions & 0 deletions packages/browser/src/mount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ export function mount(
...kernelOptions,
wheelUrls,
...makeToastKernelCallbacks(toastCallbackOptions),
workerType:
process.env.NODE_ENV === "development"
? "module" // Vite loads the worker scripts as ES modules without bundling at dev time, so we need to specify the type as "module" for the "import" statements in the worker script to work.
: "classic", // type="classic" is needed for the cross-origin worker trick to work in the page loaded via `file://` scheme, so we use it for the production build.
});

// eslint-disable-next-line react/no-deprecated
Expand Down
9 changes: 6 additions & 3 deletions packages/kernel/src/kernel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,13 @@ export interface StliteKernelOptions {

onError?: (error: Error) => void;

workerType?: WorkerOptions["type"];

sharedWorker?: boolean;

/**
* The worker to be used, which can be optionally passed.
* Desktop apps with NodeJS-backed worker is one of the use cases.
* Desktop apps with NodeJS-backed worker is one use case.
*/
worker?: globalThis.Worker;
}
Expand Down Expand Up @@ -162,8 +164,9 @@ export class StliteKernel {
// HACK: Use `CrossOriginWorkerMaker` imported as `Worker` here.
// Read the comment in `cross-origin-worker.ts` for the detail.
const workerMaker = new Worker(new URL("./worker.js", import.meta.url), {
type: "module", // Vite loads the worker scripts as ES modules without bundling at dev time, so we need to specify the type as "module" for the "import" statements in the worker script to work.
/* @vite-ignore */ shared: options.sharedWorker ?? false,
/* @vite-ignore */ // To avoid the Vite error: "[vite:worker-import-meta-url] Vite is unable to parse the worker options as the value is not static.To ignore this error, please use /* @vite-ignore */ in the worker options."
type: options.workerType,
shared: options.sharedWorker ?? false,
});
this._worker = workerMaker.worker;
}
Expand Down

0 comments on commit 8956d07

Please sign in to comment.