{"id":13624971,"url":"https://github.com/developit/workerize-loader","last_synced_at":"2025-05-14T09:08:49.687Z","repository":{"id":28237911,"uuid":"116874897","full_name":"developit/workerize-loader","owner":"developit","description":"🏗️ Automatically move a module into a Web Worker (Webpack loader)","archived":false,"fork":false,"pushed_at":"2022-06-02T23:25:47.000Z","size":729,"stargazers_count":2307,"open_issues_count":28,"forks_count":86,"subscribers_count":14,"default_branch":"main","last_synced_at":"2025-04-10T11:16:12.489Z","etag":null,"topics":["web-worker","webpack","webpack-loader","webpack-plugin","worker"],"latest_commit_sha":null,"homepage":"https://npm.im/workerize-loader","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/developit.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-01-09T21:52:09.000Z","updated_at":"2025-03-09T17:02:53.000Z","dependencies_parsed_at":"2022-07-08T02:58:12.613Z","dependency_job_id":null,"html_url":"https://github.com/developit/workerize-loader","commit_stats":null,"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/developit%2Fworkerize-loader","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/developit%2Fworkerize-loader/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/developit%2Fworkerize-loader/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/developit%2Fworkerize-loader/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/developit","download_url":"https://codeload.github.com/developit/workerize-loader/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248334960,"owners_count":21086482,"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":["web-worker","webpack","webpack-loader","webpack-plugin","worker"],"created_at":"2024-08-01T21:01:48.967Z","updated_at":"2025-04-11T03:27:07.204Z","avatar_url":"https://github.com/developit.png","language":"JavaScript","readme":"\u003cimg src=\"https://i.imgur.com/HZZG8wr.jpg\" width=\"1358\" alt=\"workerize-loader\"\u003e\n\n# workerize-loader [![npm](https://img.shields.io/npm/v/workerize-loader.svg?style=flat)](https://www.npmjs.org/package/workerize-loader) [![travis](https://travis-ci.org/developit/workerize-loader.svg?branch=master)](https://travis-ci.org/developit/workerize-loader)\n\n\u003e A webpack loader that moves a module and its dependencies into a Web Worker, automatically reflecting exported functions as asynchronous proxies.\n\n- Bundles a tiny, purpose-built RPC implementation into your app\n- If exported module methods are already async, signature is unchanged\n- Supports synchronous and asynchronous worker functions\n- Works beautifully with async/await\n- Imported value is instantiable, just a decorated `Worker`\n\n\n## Install\n\n```sh\nnpm install -D workerize-loader\n```\n\n\n### Usage\n\n**worker.js**:\n\n```js\n// block for `time` ms, then return the number of loops we could run in that time:\nexport function expensive(time) {\n    let start = Date.now(),\n        count = 0\n    while (Date.now() - start \u003c time) count++\n    return count\n}\n```\n\n**index.js**: _(our demo)_\n\n```js\nimport worker from 'workerize-loader!./worker'\n\nlet instance = worker()  // `new` is optional\n\ninstance.expensive(1000).then( count =\u003e {\n    console.log(`Ran ${count} loops`)\n})\n```\n\n### Options\n\nWorkerize options can either be defined in your Webpack configuration, or using Webpack's [syntax for inline loader options](https://webpack.js.org/concepts/loaders/#inline).\n\n#### `inline`\n\nType: `Boolean`\nDefault: `false`\n\nYou can also inline the worker as a BLOB with the `inline` parameter\n\n```js\n// webpack.config.js\n{\n  loader: 'workerize-loader',\n  options: { inline: true }\n}\n```\n\nor\n\n```js\nimport worker from 'workerize-loader?inline!./worker'\n```\n\n#### `name`\n\nType: `String`\nDefault: `[hash]`\n\nCustomize filename generation for worker bundles. Note that a `.worker` suffix will be injected automatically (`{name}.worker.js`).\n\n```js\n// webpack.config.js\n{\n  loader: 'workerize-loader',\n  options: { name: '[name].[contenthash:8]' }\n}\n```\n\nor\n\n```js\nimport worker from 'workerize-loader?name=[name].[contenthash:8]!./worker'\n```\n\n#### `publicPath`\n\nType: `String`\nDefault: based on `output.publicPath`\n\nWorkerize uses the configured value of `output.publicPath` from Webpack unless specified here. The value of `publicPath` gets prepended to bundle filenames to get their full URL. It can be a path, or a full URL with host.\n\n```js\n// webpack.config.js\n{\n  loader: 'workerize-loader',\n  options: { publicPath: '/static/' }\n}\n```\n\n#### `ready`\n\nType: `Boolean`\nDefault: `false`\n\nIf `true`, the imported \"workerized\" module will include a `ready` property, which is a Promise that resolves once the Worker has been loaded. Note: this is unnecessary in most cases, since worker methods can be called prior to the worker being loaded.\n\n```js\n// webpack.config.js\n{\n  loader: 'workerize-loader',\n  options: { ready: true }\n}\n```\n\nor\n\n```js\nimport worker from 'workerize-loader?ready!./worker'\n\nlet instance = worker()  // `new` is optional\nawait instance.ready\n```\n\n#### `import`\n\nType: `Boolean`\nDefault: `false`\n\nWhen enabled, generated output will create your Workers using a Data URL that loads your code via `importScripts` (eg: `new Worker('data:,importScripts(\"url\")')`). This workaround enables cross-origin script preloading, but Workers are created on an \"opaque origin\" and cannot access resources on the origin of their host page without CORS enabled. Only enable it if you understand this and specifically need the workaround.\n\n```js\n// webpack.config.js\n{\n  loader: 'workerize-loader',\n  options: { import: true }\n}\n```\n\nor \n\n```js\nimport worker from 'workerize-loader?import!./worker'\n```\n\n### About [Babel](https://babeljs.io/)\n\nIf you're using [Babel](https://babeljs.io/) in your build, make sure you disabled commonJS transform. Otherwize, workerize-loader won't be able to retrieve the list of exported function from your worker script :\n```js\n{\n    test: /\\.js$/,\n    loader: \"babel-loader\",\n    options: {\n        presets: [\n            [\n                \"env\",\n                {\n                    modules: false,\n                },\n            ],\n        ]\n    }\n}\n```\n\n### Polyfill Required for IE11\n\nWorkerize-loader supports browsers that support Web Workers - that's IE10+.\nHowever, these browsers require a polyfill in order to use Promises, which Workerize-loader relies on.\nIt is recommended that the polyfill be installed globally, since Webpack itself also needs Promises to load bundles.\n\nThe smallest implementation is the one we recommend installing:\n\n`npm i promise-polyfill`\n\nThen, in the module you are \"workerizing\", just add it as your first import:\n\n```js\nimport 'promise-polyfill/src/polyfill';\n```\n\nAll worker code can now use Promises. \n\n### Testing\n\n## Without Webpack\nTo test a module that is normally imported via `workerize-loader` when not using Webpack, import the module directly in your test:\n\n```diff\n-const worker = require('workerize-loader!./worker.js');\n+const worker = () =\u003e require('./worker.js');\n\nconst instance = worker();\n```\n\n## With Webpack and Jest\n\nIn Jest, it's possible to define a custom `transform` that emulates workerize-loader on the main thread.\n\nFirst, install `babel-jest` and `identity-object-proxy`:\n\n```sh\nnpm i -D babel-jest identity-object-proxy\n```\n\nThen, add these properties to the `\"transform\"` and `\"moduleNameMapper\"` sections of your Jest config (generally located in your `package.json`):\n\n```js\n{\n  \"jest\": {\n    \"moduleNameMapper\": {\n      \"workerize-loader(\\\\?.*)?!(.*)\": \"identity-obj-proxy\"\n    },\n    \"transform\": {\n      \"workerize-loader(\\\\?.*)?!(.*)\": \"\u003crootDir\u003e/workerize-jest.js\",\n      \"^.+\\\\.[jt]sx?$\": \"babel-jest\",\n      \"^.+\\\\.[jt]s?$\": \"babel-jest\"\n    }\n  }\n}\n```\n\nFinally, create the custom Jest transformer referenced above as a file `workerize-jest.js` in your project's root directory (where the package.json is):\n\n```js\nmodule.exports = {\n  process(src, filename) {\n    return `\n      async function asyncify() { return this.apply(null, arguments); }\n      module.exports = function() {\n        const w = require(${JSON.stringify(filename.replace(/^.+!/, ''))});\n        const m = {};\n        for (let i in w) m[i] = asyncify.bind(w[i]);\n        return m;\n      };\n    `;\n  }\n};\n```\n\nNow your tests and any modules they import can use `workerize-loader!` prefixes, and the imports will be turned into async functions just like they are in Workerize.\n\n### Credit\n\nThe inner workings here are heavily inspired by [worker-loader](https://github.com/webpack-contrib/worker-loader). It's worth a read!\n\n\n### License\n\n[MIT License](https://oss.ninja/mit/developit) © [Jason Miller](https://jasonformat.com)\n","funding_links":[],"categories":["JavaScript","Web Worker"],"sub_categories":["Docker Custom Builds"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevelopit%2Fworkerize-loader","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdevelopit%2Fworkerize-loader","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevelopit%2Fworkerize-loader/lists"}