Load Web Worker inside webpack library

Viewed 233

I am trying to load a web worker from inside a custom npm package.

[App] -> [my npm package -> load worker]

I use worker-loader inside the npm package to load the worker file:

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

My webpack config inside the local npm package:

{
 entry: './packages/myPackage/src/index.ts',
  output: {
    library: 'myPackage',
    libraryTarget: 'umd',
    path: path.resolve(__dirname, './packages/myPackage/dist'),
    filename: "index.js"
  },
  module: {
    rules: [
      { 
        test: /\.tsx?$/,
        loader: "ts-loader"
      },
      {
        test: /\.worker\.js$/,
        loader: 'worker-loader',
        options: {
          inline: "no-fallback"
      }
      },
    ]
  },        
}

Unfortunately every time I do so, my app cannot locate the worker file. The app is trying to get the worker from ./static/js/myPackage.worker.js but the file is not found and an error is raised Uncaught SyntaxError: Unexpected token '<'.

What am I doing wrong here? Ideally I would like the worker file to be bundled with the npm package so no additional file needs to be loaded. How can achieve this behavior?

1 Answers

Just ran into this problem myself, based on when the post was made I'm going to assume you're using Webpack5.

First, I would change the order of rules and double-check their rules are matching. Second, since you're using react-native I would verify that you can use workers.

The easiest way to not create an additional file would be to use the inline option for the worker (There's a guide for TS with them too ). Please note, for a file not to be created no-fallback will have to be used as the value for the inline option.

If that isn't an option I would probably look into module federation and the dynamic public path. If this as well is not viable then I would suggest looking into either import.meta.resolve or writing a plugin that can replace paths in the code after resolving in the Webpack dependency graph.

The inline option works like a charm, but hopefully, this helps if that isn't an option.

Cheers,
Chance

Related