{"id":13493724,"url":"https://github.com/webpack-contrib/worker-loader","last_synced_at":"2025-09-28T20:30:35.061Z","repository":{"id":4197404,"uuid":"5316517","full_name":"webpack-contrib/worker-loader","owner":"webpack-contrib","description":"A webpack loader that registers a script as a Web Worker","archived":true,"fork":false,"pushed_at":"2021-09-09T10:57:22.000Z","size":1681,"stargazers_count":1458,"open_issues_count":18,"forks_count":273,"subscribers_count":23,"default_branch":"master","last_synced_at":"2025-01-13T14:55:35.660Z","etag":null,"topics":["webpack-loader"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/webpack-contrib.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null},"funding":{"open_collective":"webpack"}},"created_at":"2012-08-06T16:25:16.000Z","updated_at":"2024-12-16T07:02:48.000Z","dependencies_parsed_at":"2022-08-02T18:00:43.986Z","dependency_job_id":null,"html_url":"https://github.com/webpack-contrib/worker-loader","commit_stats":null,"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webpack-contrib%2Fworker-loader","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webpack-contrib%2Fworker-loader/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webpack-contrib%2Fworker-loader/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webpack-contrib%2Fworker-loader/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/webpack-contrib","download_url":"https://codeload.github.com/webpack-contrib/worker-loader/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234556257,"owners_count":18851930,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["webpack-loader"],"created_at":"2024-07-31T19:01:18.166Z","updated_at":"2025-09-28T20:30:29.720Z","avatar_url":"https://github.com/webpack-contrib.png","language":"JavaScript","readme":"\u003cdiv align=\"center\"\u003e\n  \u003ca href=\"https://github.com/webpack/webpack\"\u003e\n    \u003cimg width=\"200\" height=\"200\" src=\"https://webpack.js.org/assets/icon-square-big.svg\"\u003e\n  \u003c/a\u003e\n\u003c/div\u003e\n\n[![npm][npm]][npm-url]\n[![node][node]][node-url]\n[![deps][deps]][deps-url]\n[![tests][tests]][tests-url]\n[![coverage][cover]][cover-url]\n[![chat][chat]][chat-url]\n[![size][size]][size-url]\n\n# worker-loader\n\n**DEPRECATED for v5**: https://webpack.js.org/guides/web-workers/\n\nWeb Worker loader for webpack 4.\n\nNote that this is specific to webpack 4. To use Web Workers in webpack 5, see https://webpack.js.org/guides/web-workers/.\n\n## Getting Started\n\nTo begin, you'll need to install `worker-loader`:\n\n```console\n$ npm install worker-loader --save-dev\n```\n\n### Inlined\n\n**App.js**\n\n```js\nimport Worker from \"worker-loader!./Worker.js\";\n```\n\n### Config\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.worker\\.js$/,\n        use: { loader: \"worker-loader\" },\n      },\n    ],\n  },\n};\n```\n\n**App.js**\n\n```js\nimport Worker from \"./file.worker.js\";\n\nconst worker = new Worker();\n\nworker.postMessage({ a: 1 });\nworker.onmessage = function (event) {};\n\nworker.addEventListener(\"message\", function (event) {});\n```\n\nAnd run `webpack` via your preferred method.\n\n## Options\n\n|                 Name                  |            Type             |             Default             | Description                                                                       |\n| :-----------------------------------: | :-------------------------: | :-----------------------------: | :-------------------------------------------------------------------------------- |\n|        **[`worker`](#worker)**        |     `{String\\|Object}`      |            `Worker`             | Allows to set web worker constructor name and options                             |\n|    **[`publicPath`](#publicpath)**    |    `{String\\|Function}`     |  based on `output.publicPath`   | specifies the public URL address of the output files when referenced in a browser |\n|      **[`filename`](#filename)**      |    `{String\\|Function}`     |   based on `output.filename`    | The filename of entry chunks for web workers                                      |\n| **[`chunkFilename`](#chunkfilename)** |         `{String}`          | based on `output.chunkFilename` | The filename of non-entry chunks for web workers                                  |\n|        **[`inline`](#inline)**        | `'no-fallback'\\|'fallback'` |           `undefined`           | Allow to inline the worker as a `BLOB`                                            |\n|      **[`esModule`](#esmodule)**      |         `{Boolean}`         |             `true`              | Use ES modules syntax                                                             |\n\n### `worker`\n\nType: `String|Object`\nDefault: `Worker`\n\nSet the worker type.\n\n#### `String`\n\nAllows to set web worker constructor name.\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.worker\\.(c|m)?js$/i,\n        loader: \"worker-loader\",\n        options: {\n          worker: \"SharedWorker\",\n        },\n      },\n    ],\n  },\n};\n```\n\n#### `Object`\n\nAllow to set web worker constructor name and options.\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.worker\\.(c|m)?js$/i,\n        loader: \"worker-loader\",\n        options: {\n          worker: {\n            type: \"SharedWorker\",\n            options: {\n              type: \"classic\",\n              credentials: \"omit\",\n              name: \"my-custom-worker-name\",\n            },\n          },\n        },\n      },\n    ],\n  },\n};\n```\n\n### `publicPath`\n\nType: `String|Function`\nDefault: based on `output.publicPath`\n\nThe `publicPath` specifies the public URL address of the output files when referenced in a browser.\nIf not specified, the same public path used for other webpack assets is used.\n\n#### `String`\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.worker\\.(c|m)?js$/i,\n        loader: \"worker-loader\",\n        options: {\n          publicPath: \"/scripts/workers/\",\n        },\n      },\n    ],\n  },\n};\n```\n\n#### `Function`\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.worker\\.(c|m)?js$/i,\n        loader: \"worker-loader\",\n        options: {\n          publicPath: (pathData, assetInfo) =\u003e {\n            return `/scripts/${pathData.hash}/workers/`;\n          },\n        },\n      },\n    ],\n  },\n};\n```\n\n### `filename`\n\nType: `String|Function`\nDefault: based on `output.filename`, adding `worker` suffix, for example - `output.filename: '[name].js'` value of this option will be `[name].worker.js`\n\nThe filename of entry chunks for web workers.\n\n#### `String`\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.worker\\.(c|m)?js$/i,\n        loader: \"worker-loader\",\n        options: {\n          filename: \"[name].[contenthash].worker.js\",\n        },\n      },\n    ],\n  },\n};\n```\n\n#### `Function`\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.worker\\.(c|m)?js$/i,\n        loader: \"worker-loader\",\n        options: {\n          filename: (pathData) =\u003e {\n            if (\n              /\\.worker\\.(c|m)?js$/i.test(pathData.chunk.entryModule.resource)\n            ) {\n              return \"[name].custom.worker.js\";\n            }\n\n            return \"[name].js\";\n          },\n        },\n      },\n    ],\n  },\n};\n```\n\n### `chunkFilename`\n\nType: `String`\nDefault: based on `output.chunkFilename`, adding `worker` suffix, for example - `output.chunkFilename: '[id].js'` value of this option will be `[id].worker.js`\n\nThe filename of non-entry chunks for web workers.\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.worker\\.(c|m)?js$/i,\n        loader: \"worker-loader\",\n        options: {\n          chunkFilename: \"[id].[contenthash].worker.js\",\n        },\n      },\n    ],\n  },\n};\n```\n\n### `inline`\n\nType: `'fallback' | 'no-fallback'`\nDefault: `undefined`\n\nAllow to inline the worker as a `BLOB`.\n\nInline mode with the `fallback` value will create file for browsers without support web workers, to disable this behavior just use `no-fallback` value.\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.worker\\.(c|m)?js$/i,\n        loader: \"worker-loader\",\n        options: {\n          inline: \"fallback\",\n        },\n      },\n    ],\n  },\n};\n```\n\n### `esModule`\n\nType: `Boolean`\nDefault: `true`\n\nBy default, `worker-loader` generates JS modules that use the ES modules syntax.\n\nYou can enable a CommonJS modules syntax using:\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.worker\\.(c|m)?js$/i,\n        loader: \"worker-loader\",\n        options: {\n          esModule: false,\n        },\n      },\n    ],\n  },\n};\n```\n\n## Examples\n\n### Basic\n\nThe worker file can import dependencies just like any other file:\n\n**index.js**\n\n```js\nimport Worker from \"./my.worker.js\";\n\nvar worker = new Worker();\n\nvar result;\n\nworker.onmessage = function (event) {\n  if (!result) {\n    result = document.createElement(\"div\");\n    result.setAttribute(\"id\", \"result\");\n\n    document.body.append(result);\n  }\n\n  result.innerText = JSON.stringify(event.data);\n};\n\nconst button = document.getElementById(\"button\");\n\nbutton.addEventListener(\"click\", function () {\n  worker.postMessage({ postMessage: true });\n});\n```\n\n**my.worker.js**\n\n```js\nonmessage = function (event) {\n  var workerResult = event.data;\n\n  workerResult.onmessage = true;\n\n  postMessage(workerResult);\n};\n```\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.worker\\.(c|m)?js$/i,\n        loader: \"worker-loader\",\n        options: {\n          esModule: false,\n        },\n      },\n    ],\n  },\n};\n```\n\n### Integrating with ES6+ features\n\nYou can even use ES6+ features if you have the [`babel-loader`](https://github.com/babel/babel-loader) configured.\n\n**index.js**\n\n```js\nimport Worker from \"./my.worker.js\";\n\nconst worker = new Worker();\n\nlet result;\n\nworker.onmessage = (event) =\u003e {\n  if (!result) {\n    result = document.createElement(\"div\");\n    result.setAttribute(\"id\", \"result\");\n\n    document.body.append(result);\n  }\n\n  result.innerText = JSON.stringify(event.data);\n};\n\nconst button = document.getElementById(\"button\");\n\nbutton.addEventListener(\"click\", () =\u003e {\n  worker.postMessage({ postMessage: true });\n});\n```\n\n**my.worker.js**\n\n```js\nonmessage = function (event) {\n  const workerResult = event.data;\n\n  workerResult.onmessage = true;\n\n  postMessage(workerResult);\n};\n```\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.worker\\.(c|m)?js$/i,\n        use: [\n          {\n            loader: \"worker-loader\",\n          },\n          {\n            loader: \"babel-loader\",\n            options: {\n              presets: [\"@babel/preset-env\"],\n            },\n          },\n        ],\n      },\n    ],\n  },\n};\n```\n\n### Integrating with TypeScript\n\nTo integrate with TypeScript, you will need to define a custom module for the exports of your worker.\n\n#### Loading with `worker-loader!`\n\n**typings/worker-loader.d.ts**\n\n```typescript\ndeclare module \"worker-loader!*\" {\n  // You need to change `Worker`, if you specified a different value for the `workerType` option\n  class WebpackWorker extends Worker {\n    constructor();\n  }\n\n  // Uncomment this if you set the `esModule` option to `false`\n  // export = WebpackWorker;\n  export default WebpackWorker;\n}\n```\n\n**my.worker.ts**\n\n```typescript\nconst ctx: Worker = self as any;\n\n// Post data to parent thread\nctx.postMessage({ foo: \"foo\" });\n\n// Respond to message from parent thread\nctx.addEventListener(\"message\", (event) =\u003e console.log(event));\n```\n\n**index.ts**\n\n```typescript\nimport Worker from \"worker-loader!./Worker\";\n\nconst worker = new Worker();\n\nworker.postMessage({ a: 1 });\nworker.onmessage = (event) =\u003e {};\n\nworker.addEventListener(\"message\", (event) =\u003e {});\n```\n\n#### Loading without `worker-loader!`\n\nAlternatively, you can omit the `worker-loader!` prefix passed to `import` statement by using the following notation.\nThis is useful for executing the code using a non-WebPack runtime environment\n(such as Jest with [`workerloader-jest-transformer`](https://github.com/astagi/workerloader-jest-transformer)).\n\n**typings/worker-loader.d.ts**\n\n```typescript\ndeclare module \"*.worker.ts\" {\n  // You need to change `Worker`, if you specified a different value for the `workerType` option\n  class WebpackWorker extends Worker {\n    constructor();\n  }\n\n  // Uncomment this if you set the `esModule` option to `false`\n  // export = WebpackWorker;\n  export default WebpackWorker;\n}\n```\n\n**my.worker.ts**\n\n```typescript\nconst ctx: Worker = self as any;\n\n// Post data to parent thread\nctx.postMessage({ foo: \"foo\" });\n\n// Respond to message from parent thread\nctx.addEventListener(\"message\", (event) =\u003e console.log(event));\n```\n\n**index.ts**\n\n```typescript\nimport MyWorker from \"./my.worker.ts\";\n\nconst worker = new MyWorker();\n\nworker.postMessage({ a: 1 });\nworker.onmessage = (event) =\u003e {};\n\nworker.addEventListener(\"message\", (event) =\u003e {});\n```\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      // Place this *before* the `ts-loader`.\n      {\n        test: /\\.worker\\.ts$/,\n        loader: \"worker-loader\",\n      },\n      {\n        test: /\\.ts$/,\n        loader: \"ts-loader\",\n      },\n    ],\n  },\n  resolve: {\n    extensions: [\".ts\", \".js\"],\n  },\n};\n```\n\n### Cross-Origin Policy\n\n[`WebWorkers`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) are restricted by a [same-origin policy](https://en.wikipedia.org/wiki/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.\nThis scenario can commonly occur if you are hosting your assets under a CDN domain.\nEven downloads from the `webpack-dev-server` could be blocked.\n\nThere are two workarounds:\n\nFirstly, you can inline the worker as a blob instead of downloading it as an external script via the [`inline`](#inline) parameter\n\n**App.js**\n\n```js\nimport Worker from \"./file.worker.js\";\n```\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        loader: \"worker-loader\",\n        options: { inline: \"fallback\" },\n      },\n    ],\n  },\n};\n```\n\nSecondly, you may override the base download URL for your worker script via the [`publicPath`](#publicpath) option\n\n**App.js**\n\n```js\n// This will cause the worker to be downloaded from `/workers/file.worker.js`\nimport Worker from \"./file.worker.js\";\n```\n\n**webpack.config.js**\n\n```js\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        loader: \"worker-loader\",\n        options: { publicPath: \"/workers/\" },\n      },\n    ],\n  },\n};\n```\n\n## Contributing\n\nPlease take a moment to read our contributing guidelines if you haven't yet done so.\n\n[CONTRIBUTING](./.github/CONTRIBUTING.md)\n\n## License\n\n[MIT](./LICENSE)\n\n[npm]: https://img.shields.io/npm/v/worker-loader.svg\n[npm-url]: https://npmjs.com/package/worker-loader\n[node]: https://img.shields.io/node/v/worker-loader.svg\n[node-url]: https://nodejs.org\n[deps]: https://david-dm.org/webpack-contrib/worker-loader.svg\n[deps-url]: https://david-dm.org/webpack-contrib/worker-loader\n[tests]: https://github.com/webpack-contrib/worker-loader/workflows/worker-loader/badge.svg\n[tests-url]: https://github.com/webpack-contrib/worker-loader/actions\n[cover]: https://codecov.io/gh/webpack-contrib/worker-loader/branch/master/graph/badge.svg\n[cover-url]: https://codecov.io/gh/webpack-contrib/worker-loader\n[chat]: https://badges.gitter.im/webpack/webpack.svg\n[chat-url]: https://gitter.im/webpack/webpack\n[size]: https://packagephobia.now.sh/badge?p=worker-loader\n[size-url]: https://packagephobia.now.sh/result?p=worker-loader\n","funding_links":["https://opencollective.com/webpack"],"categories":["JavaScript","Web Worker"],"sub_categories":["Docker Custom Builds"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebpack-contrib%2Fworker-loader","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwebpack-contrib%2Fworker-loader","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebpack-contrib%2Fworker-loader/lists"}