Override the path from which worker scripts are downloaded
name
To set a custom name for the output script, use the name parameter. The name may contain the string [hash], which will be replaced with a content dependent hash for caching purposes
const ctx: Worker = self as any;
// Post data to parent thread
ctx.postMessage({ foo: "foo" });
// Respond to message from parent thread
ctx.addEventListener("message", (event) => console.log(event));
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
Worker Loader
This loader registers the script as Web Worker
Install
Usage
InlinedApp.js
Configwebpack.config.js
App.js
Options
name{String}[hash].worker.jsinline{Boolean}falsefallback{Boolean}falsepublicPath{String}nullnameTo set a custom name for the output script, use the
nameparameter. The name may contain the string[hash], which will be replaced with a content dependent hash for caching purposeswebpack.config.js*
inlineYou can also inline the worker as a BLOB with the
inlineparameterwebpack.config.js
webpack.config.js
fallbackRequire a fallback for non-worker supporting environments
webpack.config.js
publicPathOverrides the path from which worker scripts are downloaded. If not specified, the same public path used for other webpack assets is used
webpack.config.js
Examples
The worker file can import dependencies just like any other file
Worker.js
Integrating with ES2015 ModulesWorker.js
Integrating with TypeScriptTo integrate with TypeScript, you will need to define a custom module for the exports of your worker
typings/custom.d.ts
Worker.ts
App.ts
Cross-Origin PolicyWebWorkersare restricted by a same-origin policy, so if yourwebpackassets 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 thewebpack-dev-servercould be blocked. There are two workaroundsFirstly, you can inline the worker as a blob instead of downloading it as an external script via the
inlineparameterApp.js
webpack.config.js
Secondly, you may override the base download URL for your worker script via the
publicPathoptionApp.js
webpack.config.js
Maintainers
Bogdan Chadkin
Juho Vepsäläinen
Joshua Wiens
Michael Ciniawsky
Alexander Krasnoyarov