javascripttypescriptweb-workerlit-element

Creating a web worker in a Stackblitz Lit Element Project?


I'm trying to create a web worker in a Lit Element Stackblitz Project.

This is the worker (worker.js):

onmessage = (e) => {
  console.log(e.data);
  postMessage(e.data);
};

And this is the code that creates it ( In my-element.ts` ):

  constructor() {
    super();
    const worker: Worker = new Worker('worker.js');
    console.log(worker);
    worker.postMessage('hello');
    worker.onmessage = (e) => {
      console.log(`The worker posted back ${e.data}`);
    };
  }

And the demo, when viewed with developer tooling, does not log any messages inside or from the worker, however it does log:

SyntaxError: Unexpected token '<' (at worker.js:1:1)

And I'm trying to figure out whether this is a Stackblitz bug and if there are any ways of getting around it?

Thoughts?


Solution

  • You have 2 ways.

    1. Use absolute path

    Since WebContainer is a file system emulated environment so its sw cannot find your worker context exactly you can

     constructor() {
        super();
        const worker: Worker = new Worker('/src/worker.js');
        console.log(worker);
        worker.postMessage('hello');
        worker.onmessage = (e) => {
          console.log(`The worker posted back ${e.data}`);
        };
      }
    

    2. Use ?worker with syntax Vite

    Since you are using vite, there is an easier way which is to use vite's syntax

    import Worker from "./worker?worker"
    
     constructor() {
        super();
        const worker: Worker = new Worker();
        console.log(worker);
        worker.postMessage('hello');
        worker.onmessage = (e) => {
          console.log(`The worker posted back ${e.data}`);
        };
      }