Search code examples
javascriptwebpackweb-workerworker-loader

How to use web worker on a npm module


I'm writing a JavaScript library and I'm using a web worker. I'm using webpack (with worker-loader) to create my build. Everything is working fine on the library.

webpack.config.js

{
    test: /app.worker.ts$/,
    include: [
        path.resolve(__dirname, 'src/')
    ],
    use: [
        {
            loader: 'babel-loader',
        },
        {
            loader: 'worker-loader',
            options: {
                name: 'app.worker.js',
            }
        }
    ]
}

That generate :

/dist/app.bundle.js // my main library build
/dist/app.worker.js // my worker build

When I try to import my library on a react-application, my library try yo load the worker like this: http://localhost:3000/dist/app.worker.js. which obviously fail because it's located in node_modules/.../dist/app.worker.js.

I probably don't use worker-loader correctly.

Thanks for your help


Solution

  • ok, I just found the problem. I don't know why but the issue is related to yarn link. If I replace the link: with file: in my package.json, I don't have the problem anymore.

    Another (non optimal) solution is to use inline:true.

    Anyone know a solution or a workaround with yarn link ? Thanks !