{"id":15637428,"url":"https://github.com/anderscan/typed-web-workers","last_synced_at":"2025-06-25T00:35:21.266Z","repository":{"id":37884883,"uuid":"89636279","full_name":"AndersCan/typed-web-workers","owner":"AndersCan","description":"Create web workers with type safety","archived":false,"fork":false,"pushed_at":"2023-01-07T04:31:18.000Z","size":2601,"stargazers_count":28,"open_issues_count":18,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-04-15T06:14:17.694Z","etag":null,"topics":["typescript","web-worker"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","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/AndersCan.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-04-27T20:09:55.000Z","updated_at":"2024-03-30T11:34:09.000Z","dependencies_parsed_at":"2023-02-06T11:46:48.022Z","dependency_job_id":null,"html_url":"https://github.com/AndersCan/typed-web-workers","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/AndersCan%2Ftyped-web-workers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AndersCan%2Ftyped-web-workers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AndersCan%2Ftyped-web-workers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AndersCan%2Ftyped-web-workers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AndersCan","download_url":"https://codeload.github.com/AndersCan/typed-web-workers/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249016641,"owners_count":21198833,"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":["typescript","web-worker"],"created_at":"2024-10-03T11:11:37.492Z","updated_at":"2025-04-15T06:14:24.697Z","avatar_url":"https://github.com/AndersCan.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# typed-web-workers\n[![npm version](https://img.shields.io/npm/v/typed-web-workers.svg?style=flat)](https://www.npmjs.com/package/typed-web-workers)[![Dependabot Status](https://api.dependabot.com/badges/status?host=github\u0026repo=AndersCan/typed-web-workers)](https://dependabot.com)[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)\n\nLibrary that help you get quickly up and running with web workers in **TypeScript** or **JavaScript** projects.\n\n\u003e ❗️❗️❗️ The `workerFunction` is executed in an **isolated context**. It can not rely on its surrounding context. Use `importScripts` if you need something added to the worker context\n\n# Installation\n`npm install typed-web-workers`\n\n# tl;dr\n```javascript\nimport { createWorker } from 'typed-web-workers'\n\nconst worker = createWorker({\n  workerFunction: ({input, callback}) =\u003e callback(input * 2),\n  onMessage: result =\u003e console.log(`Worker returned: ${result}`),\n  onError: error =\u003e console.log(`unhandled exception in Worker`)\n})\nworker.postMessage(1) // Worker returned: 2\nworker.postMessage(2) // Worker returned: 4\n\n```\nOnly `workerFunction` is required by `createWorker`.\n\n## Fiddles\n[ESM example](https://jsfiddle.net/anderscan/80y7xLwe/), [IIFE example](https://jsfiddle.net/anderscan/uw51genv/)\n\n## Motivation for Web Workers\n- avoid blocking the main thread with long running tasks\n\nWhen the main thread is blocked, the UI will be unresponsive to user events.\n\n\u003e **Note** Using a web worker does not make a function run [faster](https://youtu.be/7Rrv9qFMWNM?t=1503). \n\n## Motivation for Typed Web Workers\n- a fully typesafe web worker\n- quickly created\n- all of the benefits of a _native_ web worker\n\n\n# Usage\n\n## Worker with local state\n\n```javascript\n/**\n * Function that will be executed on the Worker\n * */\nfunction workerFunction({\n  input,\n  callback,\n  getState,\n  setState\n}: WorkerFunctionProps\u003cnumber, number, number\u003e) {\n  const previousValue = getState() || 0\n  callback(previousValue + input)\n  setState(input)\n}\n\n createWorker({\n  workerFunction,\n  onMessage: data =\u003e console.log(data)\n})\n```\n\n## Worker with `moment.js` \n\n```javascript\nconst momentWorker = createWorker({\n  workerFunction: ({input,callback}) =\u003e callback(moment(input).format('YYYY')),\n  onMessage: data =\u003e console.log(data)\n  importScripts: [\n    'https://unpkg.com/moment@2.22.2/min/moment.min.js'\n  ]\n})\n```\n\n### importScripts\n Use `importScripts` to import external files into your Worker [(mdn docs)](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts).\n\nThe provided URIs in `importScripts` must link to a JavaScript file that can be loaded by the Worker at runtime. The scripts must be CommonJs/umd as Workers do not support ES modules.\n\nIf something goes wrong during the import an exception will be thrown and `onError` will be called. If this happens, you can assume the worker is no longer responsive.\n\n### Using local files\n\u003e How you solve this depends on how you build and deploy your project.\n\nYou will most likely need to create a new entrypoint bundle that you can import with `importScripts`. For example `importScripts[\"www.example.com/public/my-script.js\"]`.\n\n# Worker Scope\nThe `workerFunction` that we give our worker can **only** use the data provided from the `input` variable, from its state and from `importScripts`. It does not have access to variables or functions outside its scope.\n\n```javascript\nconst results = []\nfunction workerFunction({input, callback}) {\n  results.push(input.x + input.y) // this would not work\n}\n```\nIt will compile, but would not work because the two variables are not in the same context/thread.\n\n```javascript\nconst results = [] // main context\nfunction workerFunction({input, callback}) {\n  results.push(input.x + input.y) // worker context\n}\n```\n\n# How does this work?\nIn short, `createWorker`:\n1. Converts your `workerFunction` to a string\n2. Creates a new _native_ Worker using this string (by using Blob)\n3. returns a instance of a `TypedWorker` that acts as a wrapper to the _native_ worker.\n\nCheck the source code of `TypedWorker.ts` if you want more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanderscan%2Ftyped-web-workers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fanderscan%2Ftyped-web-workers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanderscan%2Ftyped-web-workers/lists"}