Skip to content

jason-rietzke/simple-worker-vite

Repository files navigation

Simple Worker Vite

stars License npm version npm Deploy Docs build


easy way to use web workers with vite

📝 Table of Contents

🧐 About

A vite plugin to simplify the way you can use web workers in your vite project.
It allows you to specify the worker files in your vite config and then compile them into separate files that can be used in your project.

🚀 Usage

Install

npm install simple-worker-vite

Add to vite config

// vite.config.js
import { defineConfig } from "vite";
import { simpleWorkerPlugin, workersFromDir } from "simple-worker-vite/plugin";

export default defineConfig({
	plugins: [
		simpleWorkerPlugin({
			workers: workersFromDir("src/workers/"),
		}),
	],
});

This will search the src/workers/ directory for any files ending in .worker.ts or .worker.js and compile them as modules into separate files that can be found in the dist/workers/ directory (by default).

WorkerStore utility

The WorkerStore utility can be used to make it easier to use the workers in your project.

import { WorkerStore } from "simple-worker-vite";
const workerStore = new WorkerStore();

workerStore
	.spawn("my-worker-name")
	.then((worker) => {
		worker.addEventListener("message", (event) => {
			console.log(event.data);
		});
		worker.postMessage(["Hello", "World"]);
	})
	.catch(console.error);

The WorkerStore will automatically load the worker from the /workers/ path (by default) and spawn it as a new worker.
Form there on you can use the worker as you normally would.

For more information on how to use the library, see the documentation.

⛏️ Built Using

✍️ Authors