aboutsummaryrefslogtreecommitdiff
path: root/docs/api/workers.md
diff options
context:
space:
mode:
Diffstat (limited to 'docs/api/workers.md')
-rw-r--r--docs/api/workers.md21
1 files changed, 15 insertions, 6 deletions
diff --git a/docs/api/workers.md b/docs/api/workers.md
index 417b77148..2b8c4fe13 100644
--- a/docs/api/workers.md
+++ b/docs/api/workers.md
@@ -10,7 +10,7 @@ Bun implements a minimal version of the [Web Workers API](https://developer.mozi
Like in browsers, [`Worker`](https://developer.mozilla.org/en-US/docs/Web/API/Worker) is a global. Use it to create a new worker thread.
-From the main thread:
+### From the main thread
```js#Main_thread
const workerURL = new URL("worker.ts", import.meta.url).href;
@@ -22,16 +22,25 @@ worker.onmessage = event => {
};
```
-Worker thread:
+### Worker thread
```ts#worker.ts_(Worker_thread)
+// prevents TS errors
+declare var self: Worker;
+
self.onmessage = (event: MessageEvent) => {
console.log(event.data);
postMessage("world");
};
```
-You can use `import`/`export` syntax in your worker code. Unlike in browsers, there's no need to specify `{type: "module"}` to use ES Modules.
+To prevent TypeScript errors when using `self`, add this line to the top of your worker file.
+
+```ts
+declare var self: Worker;
+```
+
+You can use `import` and `export` syntax in your worker code. Unlike in browsers, there's no need to specify `{type: "module"}` to use ES Modules.
To simplify error handling, the initial script to load is resolved at the time `new Worker(url)` is called.
@@ -123,14 +132,14 @@ By default, an active `Worker` will keep the main (spawning) process alive, so a
### `worker.unref()`
-To stop a running worker from keeping the process alive, call `worker.unref()`. This decouples the lifetime of the worker to the lifetime of the main process, and is equivlent to what Node.js' `worker_threads` does.
+To stop a running worker from keeping the process alive, call `worker.unref()`. This decouples the lifetime of the worker to the lifetime of the main process, and is equivalent to what Node.js' `worker_threads` does.
```ts
const worker = new Worker(new URL("worker.ts", import.meta.url).href);
worker.unref();
```
-Note: `worker.unref()` is not available in browers.
+Note: `worker.unref()` is not available in browsers.
### `worker.ref()`
@@ -151,7 +160,7 @@ const worker = new Worker(new URL("worker.ts", import.meta.url).href, {
});
```
-Note: `worker.ref()` is not available in browers.
+Note: `worker.ref()` is not available in browsers.
## Memory usage with `smol`