title: Using Web Workers with React and Webpack 5
body: <p>I have been trying to use Web Workers with react for a few days and I ran into a few issues.</p>
  <p>I started with a create-react-app using webpack 4. I could use a web worker using this tutorial: <a href="https://javascript.plainenglish.io/web-worker-in-react-9b2efafe309c" rel="nofollow noreferrer">https://javascript.plainenglish.io/web-worker-in-react-9b2efafe309c</a> which loads a WebWorker that way:</p>
  <pre class="lang-js prettyprint-override"><code>export default class WorkerBuilder extends Worker {
    constructor(worker) {
      const code = worker.toString();
      const blob = new Blob([`(${code})()`]);
      return new Worker(URL.createObjectURL(blob));
    }
  }
  </code></pre>
  <p>Unfortunately I need to use a lib from my worker (d3-delaunay) and webpack gave me an error when I tried to do so (I think it changed its path).</p>
  <p>I heard about worker-loader and I learned that this had been deprecated since Web Worker importing is now built in webpack 5.</p>
  <p>I updated my app to WebPack 5 (as explained in the create-react-app wiki), this was not easy since a lot of my dependencies broke.</p>
  <p>But when I tried to load my WebWorker as explained here: <a href="https://webpack.js.org/guides/web-workers/" rel="nofollow noreferrer">https://webpack.js.org/guides/web-workers/</a>
  this didn't work at all (no errors).</p>
  <p>That's my code:</p>
  <pre class="lang-js prettyprint-override"><code>console.log(&quot;hello&quot;);
  const worker = new Worker(new URL('./world.worker.js', import.meta.url));
  worker.postMessage({
      question:
          'The Answer to the Ultimate Question of Life, The Universe, and Everything.',
  });
  worker.onmessage = ({ data: { answer } }) =&gt; {
      console.log(answer);
  };
  console.log(&quot;world&quot;);
  </code></pre>
  <p>And my world.worker.js:</p>
  <pre class="lang-js prettyprint-override"><code>import { Delaunay } from &quot;d3-delaunay&quot;;
  
  // eslint-disable-next-line import/no-anonymous-default-export
  export default () =&gt; {
      // eslint-disable-next-line no-restricted-globals
      self.onmessage = (message) =&gt; {
          console.log(&quot;yolo&quot;);
      };
  };
  </code></pre>
  <p>But my only output was:</p>
  <pre><code>hello
  world
  </code></pre>
  <p>My worker didn't seem to work.</p>