easy way to use web workers with vite
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.
npm install simple-worker-vite
// 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).
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.
- esbuild - Bundler
- Vite - Bundler
- TypeScript - Language
- Vitepress - Documentation