Skip to content

Commit 06f5795

Browse files
authored
Merge pull request #249 from andywer/feature/211-blob-worker
Implement BlobWorker
2 parents 5fd9188 + 63b9599 commit 06f5795

18 files changed

+607
-178
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
.cache/
22
.vscode/
3+
bundle/
34
docs/_site
45
docs/vendor
56
dist/*
67
dist-*/*
78
node_modules/
89
test/rollup/dist/
9-
test/webpack/dist*
10+
test/webpack/dist/
1011
test/workers/*.js
1112
.DS_Store
1213
Thumbs.db

docs/usage.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,29 @@ try {
143143
}
144144
```
145145

146+
## Blob workers
147+
148+
Sometimes you need to ship master and worker code in a single file. There is an alternative way to create a worker for those situations, allowing you to inline the worker code in the master code.
149+
150+
The `BlobWorker` class works just like the regular `Worker` class, but instead of taking a path to a worker, the constructor takes the worker source code as a binary blob.
151+
152+
There is also a convenience function `BlobWorker.fromText()` that creates a new `BlobWorker`, but allows you to pass a source string instead of a binary buffer.
153+
154+
Here is a webpack-based example, leveraging the `raw-loader` to inline the worker code. The worker code that we load using the `raw-loader` is the content of bundles that have been created by two previous webpack runs: one worker build targetting node.js, one for web browsers.
155+
156+
```js
157+
import { spawn, BlobWorker } from "threads"
158+
import MyWorkerNode from "raw-loader!../dist/worker.node/worker.js"
159+
import MyWorkerWeb from "raw-loader!../dist/worker.web/worker.js"
160+
161+
const MyWorker = process.browser ? MyWorkerWeb : MyWorkerNode
162+
163+
const worker = await spawn(BlobWorker.fromText(MyWorker))
164+
// Now use this worker as always
165+
```
166+
167+
Bundle this module and you will obtain a stand-alone bundle that has its worker inlined. This is particularly useful for libraries using threads.js.
168+
146169
## TypeScript
147170

148171
### Type-safe workers

0 commit comments

Comments
 (0)