import Worker from "./file.worker.js";const worker = new Worker();worker.postMessage({ a: 1 });worker.onmessage = function (event) {};worker.addEventListener("message", function (event) {});
Type: String|Function
Default: based on output.publicPath
The publicPath specifies the public URL address of the output files when referenced in a browser.
If not specified, the same public path used for other webpack assets is used.
Type: String|Function
Default: based on output.filename, adding worker suffix, for example - output.filename: '[name].js' value of this option will be [name].worker.js
Type: String
Default: based on output.chunkFilename, adding worker suffix, for example - output.chunkFilename: '[id].js' value of this option will be [id].worker.js
To integrate with TypeScript, you will need to define a custom module for the exports of your worker.
typings/worker-loader.d.ts
declare module "worker-loader!*" { // You need to change `Worker`, if you specified a different value for the `workerType` option class WebpackWorker extends Worker { constructor(); } // Uncomment this if you set the `esModule` option to `false` // export = WebpackWorker; export default WebpackWorker;}
my.worker.ts
const ctx: Worker = self as any;// Post data to parent threadctx.postMessage({ foo: "foo" });// Respond to message from parent threadctx.addEventListener("message", (event) => console.log(event));
index.ts
import Worker from "worker-loader!./Worker";const worker = new Worker();worker.postMessage({ a: 1 });worker.onmessage = (event) => {};worker.addEventListener("message", (event) => {});
Cross-Origin Policy
WebWorkers are restricted by a same-origin policy, so if your webpack assets are not being served from the same origin as your application, their download may be blocked by your browser.
This scenario can commonly occur if you are hosting your assets under a CDN domain.
Even downloads from the webpack-dev-server could be blocked.
There are two workarounds:
Firstly, you can inline the worker as a blob instead of downloading it as an external script via the inline parameter