UNPKG

3.8 kBMarkdownView Raw
1<p align="center">
2 <img src="https://i.imgur.com/cLb2dLG.jpg" width="600" alt="comlink-loader">
3</p>
4<h1 align="center">🛰 comlink-loader 📡</h1>
5<p align="center">Offload modules to Worker threads seamlessly using <a href="https://github.com/GoogleChromeLabs/comlink">Comlink</a>.</p>
6
7
8### Features
9
10- Offload almost any module into a Worker with little or no usage change
11- Supports arbitrary classes, objects & functions (`await new Foo()`)
12- Works beautifully with async/await
13- Built-in code-splitting: workers are lazy-loaded
14
15
16## Installation
17
18```sh
19npm install -D comlink-loader
20```
21
22
23## Usage
24
25The goal of `comlink-loader` is to make the fact that a module is running inside a Worker nearly transparent to the developer.
26
27### Factory Mode (default)
28
29In the example below, there are two changes we must make in order to import `MyClass` within a Worker via `comlink-loader`.
30
311. instantiation and method calls must be prefixed with `await`, since everything is inherently asynchronous.
322. the value we import from `comlink-loader!./my-class` is now a function that returns our module exports.
33 > Calling this function creates a new instance of the Worker.
34
35**my-class.js**: _(gets moved into a worker)_
36
37```js
38// Dependencies get bundled into the worker:
39import rnd from 'random-int';
40
41// Export as you would in a normal module:
42export function meaningOfLife() {
43 return 42;
44}
45
46export class MyClass {
47 constructor(value = rnd()) {
48 this.value = value;
49 }
50 increment() {
51 this.value++;
52 }
53 // Tip: async functions make the interface identical
54 async getValue() {
55 return this.value;
56 }
57}
58```
59
60**main.js**: _(our demo, on the main thread)_
61
62```js
63import MyWorker from 'comlink-loader!./my-class';
64
65// instantiate a new Worker with our code in it:
66const inst = new MyWorker();
67
68// our module exports are exposed on the instance:
69await inst.meaningOfLife(); // 42
70
71// instantiate a class in the worker (does not create a new worker).
72// notice the `await` here:
73const obj = await new inst.MyClass(42);
74
75await obj.increment();
76
77await obj.getValue(); // 43
78```
79
80### Singleton Mode
81
82Comlink-loader also includes a `singleton` mode, which can be opted in on a per-module basis using Webpack's inline loader syntax, or globally in Webpack configuration. Singleton mode is designed to be the easiest possible way to use a Web Worker, but in doing so it only allows using a single Worker instance for each module.
83
84The benefit is that your module's exports can be used just like any other import, without the need for a constructor. It also supports TypeScript automatically, since the module being imported looks just like it would were it running on the main thread. The only change that is required in order to move a module into a Worker using singleton mode is to ensure all of your function calls use `await`.
85
86First, configure `comlink-loader` globally to apply to all `*.worker.js` files (or whichever pattern you choose). Here we're going to use TypeScript, just to show that it works out-of-the-box:
87
88**webpack.config.js**:
89
90```js
91module.exports = {
92 module: {
93 rules: [
94 {
95 test: /\.worker\.(js|ts)$/i,
96 use: [{
97 loader: 'comlink-loader',
98 options: {
99 singleton: true
100 }
101 }]
102 }
103 ]
104 }
105}
106```
107
108Now, let's write a simple module that we're going to load in a Worker:
109
110**greetings.worker.ts**:
111
112```ts
113export async function greet(subject: string): string {
114 return `Hello, ${subject}!`;
115}
116```
117
118We can import our the above module, and since the filename includes `.worker.ts`, it will be transparently loaded in a Web Worker!
119
120**index.ts**:
121
122```ts
123import { greet } from './greetings.worker.ts';
124
125async function demo() {
126 console.log(await greet('dog'));
127}
128
129demo();
130```
131
132
133## License
134
135Apache-2.0