Wordpressor
Wordpressor

Reputation: 7543

JS - creating new worker causes 404

I'm using Worker API to create new worker, it's as simple as:

var myWorker = new Worker('src/worker.js');

Unfortunately I'm using webpack to build my project and linking to src/worker.js returns 404.

How can I use it to create my Worker?

import hardWorker from './src/hardWorker.js';
var myWorker = new Worker(HOW TO PUT HARDWORKER HERE?);

Upvotes: 0

Views: 1844

Answers (2)

Garrett Johnson
Garrett Johnson

Reputation: 2534

The issue is that the worker API expects a URL to load the work script from and webpack tries to bundle everything into a single file, meaning the src/worker.js file isn't where it needs to be when the browser tries to load it.

There are a couple options.

  • You could manually copy the worker.js file to wherever the build is trying to load the file from.
  • You could set up webpack to copy the file to the right location using the CopyWebpackPlugin.
  • Depending on how complicated your worker is, you could just put the code in a string and create an object URL so the browser doesn't have to load anything from the server at all. This is an approach I've used in the past and have written a helper library for to Workers a little easier to use.

Hope that helps!

Upvotes: 4

lTyl
lTyl

Reputation: 156

Try using the worker-loader plugin for webpack, which can be found here: https://github.com/webpack-contrib/worker-loader

This registers scripts loaded through it as a Web worker, and bundles all of your workers in the main bundle that webpack creates. Using it in your app is as simple as this:

import MyWorker from 'worker-loader!./Worker.js';
const worker = new MyWorker();

Or you can add loader configuration parameters to your webpack.config so all files matching a specific pattern are loaded and registered as workers. The worker-loader has an example of this.

Upvotes: 4

Related Questions