Skip to content

egoist/typed-worker

main
Switch branches/tags
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
src
 
 
 
 
 
 
 
 
 
 
 
 
 
 

💛 You can help the author become a full-time open-source maintainer by sponsoring him on GitHub.


typed-worker

npm version npm downloads paka type docs

Install

npm i typed-worker

Usage

Create a worker.ts:

import { handleActions } from "typed-worker"

export const actions = {
  async sum(a: number, b: number) {
    await someHeavyOperation()
    return a + b
  },
}

export type Actions = typeof actions

handleActions(actions)

In your app.ts where you want to use the worker:

import { createWorker } from "typed-worker"
import { type Actions } from "./worker"

const worker = createWorker<Actions>(
  // Require a bundler like Vite, webpack etc
  () =>
    new Worker(new URL("./worker.ts", import.meta.url), {
      type: "module",
    }),
)

const result = await worker.run("sum", 1, 2)

expect(result).toBe(3)

To use the worker.ts in an iframe instead of a web worker, you only need to return the iframe element in createWorker instead:

const iframe = createWorker<Actions>(
  () => document.querySelector<HTMLIframeElement>("#your-iframe-element")!,
)

const result = await iframe.run("sum", 1, 2)

Error handling

Errors thrown in the worker will be re-thrown when you call the .run method:

worker.run("some-problematic-action").catch((err) => {
  // err is the error thrown in the worker
})

Sponsors

sponsors

License

MIT © EGOIST

About

Type-safe and Promisified API for Web Worker and Iframe

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published