What is the good way to lint SharedWorker code using eslint inside Vue application that runs on Vite

33 Views Asked by At

I have a standard Vue 3/Vite application scaffolded using

npm create vue

I am using eslint in the project and I want to add a SharedWorker to my app. I have created worker.js file inside the project, where onconnect handler is defined. With that setup I get eslint error message:

'onconnect' is not defined. eslint(no-undef)

How can I avoid this error without silencing it and make sure worker.js is linted properly?

1

There are 1 best solutions below

0
kerms On

My workaround is:

  1. in your tsconfig.app.json add to compilerOptions.lib
{
  /* other stufs */
  "compilerOptions": {
    "lib": [
      "DOM", /* for document.* */
      "WebWorker", /* for *WorkerGlobalScope */
    ]
  }
}
  1. Then in your worker.ts|.js add declare const self: SharedWorkerGlobalScope; at the top of your file
  2. to use onconnectadd self before like this
self.onconnect = function(event) {
    const port = event.ports[0];
    console.log(port)

    port.onmessage = function(e) {
        console.log('Received message in SharedWorker:', e.data);
        // Process the received string data here
    };
};