Reference worker relative to JavaScript file

624 Views Asked by At

I'm using webpack to put together a project which uses Web Workers. To accomplish this, I'm using the worker-loader loader.

I've made a minimal plunk to demonstrate my environment (I'll also paste the code below for posterity).

The problem is, the resolution of the worker file isn't behaving as expected. If I launch index.html (I'm serving the root folder with an HTTP server), it can naturally resolve ../dist/TestMain.js, but it tries to resolve TestWorker.js from ./ relative to index.html. I'd like it to resolve from ./ relative to TestMain.js.

I've tried adding output.publicPath = "./", but that didn't help. I've searched the documentation (and worker-loader's documentation) for similar options, but haven't found anything that I can say is relevant (I could be wrong).

Normally, I'd be all for using resolve.alias, but the output should be able to be dropped into any folder (the main JS file and worker JS file would remain together in the same folder) referable by the HTML page.

I also saw I can in-line the worker, but I'd like to avoid that since it blobs the worker (can cause other kinds of referencing problems).

Are there options I'm missing to enable relative referencing, or a workaround I've missed?

Here's the structure:

Project
 |- dist
 |   |- TestMain.js
 |   |- TestWorker.js
 |- src
 |   |- workers
 |   |   |- TestWorker.js
 |   |- index.js
 |- test
 |   |- index.html
 |- webpack.config.js

Here's my webpack.config.js:

const path = require("path");

module.exports = {
  entry: "./src/index.js",
  mode: "development",
  output: {
    filename: "TestMain.js",
    path: path.resolve(__dirname, "dist"),
    library: "MyLib",
    libraryTarget: "umd"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: [
          path.resolve(__dirname, "src/workers"),
        ],
        use: {
          loader: "worker-loader",
          options: {
            name: "[name].js"
          }
        }
      }
    ]
  }
};

I'll share my other files if you want, but it does work if the worker file is in the same folder as index.html.

1

There are 1 best solutions below

3
On

Specify publicPath option for worker-loader:

        use: {
          loader: "worker-loader",
          options: {
            name: "[name].js",
            publicPath: "/dist"
          }
        }

Alternatively, you might consider adding a step to your build process that copies static assets, including index.html, to the dist folder.