hmsk / vite-plugin-elm

A plugin for Vite enables you to compile an Elm application/document/element
https://www.npmjs.com/package/vite-plugin-elm
Other
201 stars 31 forks source link

Using elm in Web Worker fails with Uncaught ReferenceError: document is not defined #756

Open jakub-nlx opened 4 days ago

jakub-nlx commented 4 days ago

Describe the bug If you attempt to start a Platform.worker app in a Web Worker script, you get

Worker.elm?import:23902 Uncaught ReferenceError: document is not defined

Reproducible repo

The gist is:

Worker.elm:

module Worker exposing (main)

main = Platform.worker
        { init = init
        , update = update
        , subscriptions = subscriptions
        }

worker.ts:

import { Elm } from "./Worker.elm";

addEventListener("message", (event) => {
    const app = Elm.Validator.Worker.init({
      flags: event.data,
    });
    const subscriber = (val: T): void => {
      app.ports.sendResult.unsubscribe(subscriber);
      postMessage(val);
    };
    app.ports.sendResult.subscribe(subscriber);
  }
});

index.ts:

  const worker = new Worker(
    new URL("./worker.ts", import.meta.url),
    { type: "module" },
  );

  worker.postMessage({});

Expected behavior No errors.

Additional context This seems to be a problem with the injected HMR code that assumes a standard browser context, but doesn't work in a Web Worker context (where globals like document are not defined).

Workaround

Plonking globalThis.document = {} at the top of the worker code makes it sort of usable, but HMR updates will still crash it.