Skip to content

mchao123/better-webworker

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

better-webworker

A TypeScript-friendly wrapper for Web Workers that makes them easier to use with type safety.

中文 | English

Installation

npm i better-webworker

Configuration

// vite.config.ts
import { defineConfig } from 'vite'
import betterWebworker from 'better-webworker/vite.mjs'

export default defineConfig({
  plugins: [
    betterWebworker() // Default pattern: .worker.ts
    // Or customize pattern:
    // betterWebworker(/\.worker\.(ts|js)$/)
  ],
})

Basic Usage

// test.worker.ts
import { defineReceive } from 'better-webworker'

const ping = (str: string) => {
    console.log(str);
    return 'pong ' + str
}

export default defineReceive({
    ping
});

Advanced Usage

// ...
const { methods, cb, worker } = useWorker();
const { handleBuffer } = methods;
const buf = new ArrayBuffer(100000);

handleBuffer.transfer = [buf]; // 传递ArrayBuffer
handleBuffer.timeout = 10000; // 设置超时时间
handleBuffer(buf, cb((newBuf) => {
    console.log('done', newBuf);
    worker.terminate(); // 关闭worker
}));
// ...

Notes

The default function will be executed as a string in the worker thread. If you need to use a callback, please wrap it with cb().

Other

I'm not very good at writing documentation. If you have any questions, please feel free to open an issue.

License

MIT

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published