vite-plugin-node-worker
Version:
Vite plugin for Node.js worker threads. Supports DEV and BUILD modes.
101 lines (67 loc) • 2.22 kB
Markdown
and build ViteJS projects with [Node Worker Threads](https://nodejs.org/api/worker_threads.html).
* Supports DEV and BUILD mode
* Transforms Workers writen in TypeScript.
* respects alias configuration in vite.config.ts
```bash
npm install vite-plugin-node-worker
```
```ts
// ./vite.config.ts
import { defineConfig } from "vite";
import workerPlugin from "vite-plugin-node-worker";
export default defineConfig({
plugins: [workerPlugin()],
worker: {
plugins: () => [workerPlugin()],
},
});
```
**Note:** `worker: {}` applys the transformation in ViteJS Dev Mode.
The path to the worker file needs to be suffixed with `?nodeWorker` or `?modulePath`.
**Wrapper Mode**
```ts
import ApiWorker from "./api-worker.ts?nodeWorker";
const apiW = ApiWorker({ workerData: { hello: "world" } });
api.postMessage("MSG")
```
transforms `import ApiWorker from "./api-worker.ts?nodeWorker";` to:
```js
import { Worker } from 'node:worker_threads';
export default function (options) { return new Worker(new URL(${assetRefId}, import.meta.url), options) }
```
**Path Export**
```ts
import ApiWorkerPath from "./api-worker.ts?modulePath";
import { Worker } from "node:worker_threads"
const apiW = new Worker(workerPath, { workerData: { hello: "world" } });
api.postMessage("MSG")
```
transforms `import ApiWorkerPath from "./api-worker.ts?modulePath";` to:
```js
export default ${assetRefId}
```
**Clean Cache:**
```bash
rm -rf node_modules/.vite-plugin-node-worker
```
**Activate Debug**
```bash
VNW_DEBUG=1 npm run dev
```
**Worker Naming Clash**
By default vite will place the worker in the root of the build target directory.
If two worker have the same name they will be overwriten. Use different names or config vite to add a file hash to worker files.
This plugin is based on code from:
- https://www.npmjs.com/package/@fetsorn/vite-node-worker
- https://github.com/alex8088/electron-vite/blob/master/src/plugins/worker.ts
The difference is the support of the ViteJS DEV mode.
[ ](LICENSE)
A plugin to serve