Skip to content

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

@jakub-nlx

Description

@jakub-nlx

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions