0
# Worker Loader
1
2
Worker Loader is a webpack loader that enables developers to easily integrate Web Workers into their webpack-bundled applications. It provides flexible configuration options for worker instantiation, customizable filename patterns, inline mode for embedding workers as BLOBs, and seamless integration with modern JavaScript features.
3
4
## Package Information
5
6
- **Package Name**: worker-loader
7
- **Package Type**: npm (webpack loader)
8
- **Language**: JavaScript
9
- **Installation**: `npm install worker-loader --save-dev`
10
- **Peer Dependencies**: webpack@^4.0.0 || ^5.0.0
11
12
## Core Imports
13
14
Worker Loader generates factory functions that can be imported using standard ES modules or CommonJS syntax:
15
16
```javascript
17
// ES modules (default, when esModule: true)
18
import Worker from "./my.worker.js";
19
20
// CommonJS (when esModule: false)
21
const Worker = require("./my.worker.js");
22
23
// Inline loader syntax (ES modules)
24
import Worker from "worker-loader!./Worker.js";
25
26
// Inline loader syntax (CommonJS)
27
const Worker = require("worker-loader!./Worker.js");
28
```
29
30
## Core Usage
31
32
Worker Loader can be used in two primary ways:
33
34
### Webpack Configuration
35
36
```javascript
37
module.exports = {
38
module: {
39
rules: [
40
{
41
test: /\.worker\.(c|m)?js$/,
42
use: {
43
loader: "worker-loader",
44
options: {
45
// Configuration options
46
},
47
},
48
},
49
],
50
},
51
};
52
```
53
54
### Inline Loader Syntax
55
56
```javascript
57
import Worker from "worker-loader!./Worker.js";
58
59
// With options as query parameters
60
import Worker from "worker-loader?filename=custom.worker.js!./Worker.js";
61
```
62
63
## Basic Usage
64
65
```javascript
66
// 1. Create a worker file (e.g., my.worker.js)
67
// my.worker.js
68
onmessage = function (event) {
69
const workerResult = event.data;
70
workerResult.processed = true;
71
postMessage(workerResult);
72
};
73
74
// 2. Import and use the worker in your main application
75
import Worker from "./my.worker.js";
76
77
const worker = new Worker();
78
79
worker.onmessage = function (event) {
80
console.log("Received from worker:", event.data);
81
};
82
83
worker.postMessage({ data: "Hello worker!" });
84
```
85
86
## Capabilities
87
88
### Worker Instantiation
89
90
Creates Web Worker or SharedWorker instances with customizable constructor options.
91
92
```javascript { .api }
93
// Generated worker factory function interface
94
interface WorkerFactory {
95
(): Worker | SharedWorker;
96
}
97
98
// Configuration for worker type
99
interface WorkerTypeConfig {
100
type: string; // Constructor name (e.g., "Worker", "SharedWorker")
101
options?: WorkerOptions; // Worker constructor options
102
}
103
104
interface WorkerOptions {
105
type?: "classic" | "module";
106
credentials?: "omit" | "same-origin" | "include";
107
name?: string;
108
}
109
```
110
111
### Loader Configuration
112
113
Configure the loader behavior through webpack configuration options.
114
115
```javascript { .api }
116
interface WorkerLoaderOptions {
117
worker?: string | WorkerTypeConfig; // Default: "Worker"
118
publicPath?: string | ((pathData: any, assetInfo: any) => string);
119
filename?: string | ((pathData: any) => string);
120
chunkFilename?: string;
121
inline?: "no-fallback" | "fallback";
122
esModule?: boolean; // Default: true
123
}
124
```
125
126
#### Worker Option
127
128
Specifies the worker constructor type and options.
129
130
**String format:**
131
```javascript
132
{
133
worker: "SharedWorker"
134
}
135
```
136
137
**Object format:**
138
```javascript
139
{
140
worker: {
141
type: "SharedWorker",
142
options: {
143
type: "classic",
144
credentials: "omit",
145
name: "my-custom-worker-name"
146
}
147
}
148
}
149
```
150
151
#### PublicPath Option
152
153
Controls the public URL path for worker files.
154
155
**String format:**
156
```javascript
157
{
158
publicPath: "/scripts/workers/"
159
}
160
```
161
162
**Function format:**
163
```javascript
164
{
165
publicPath: (pathData, assetInfo) => {
166
return `/scripts/${pathData.hash}/workers/`;
167
}
168
}
169
```
170
171
#### Filename Option
172
173
Customizes the filename pattern for worker entry chunks.
174
175
**String format:**
176
```javascript
177
{
178
filename: "[name].[contenthash].worker.js"
179
}
180
```
181
182
**Function format:**
183
```javascript
184
{
185
filename: (pathData) => {
186
if (/\.worker\.(c|m)?js$/i.test(pathData.chunk.entryModule.resource)) {
187
return "[name].custom.worker.js";
188
}
189
return "[name].js";
190
}
191
}
192
```
193
194
#### ChunkFilename Option
195
196
Sets the filename pattern for worker non-entry chunks.
197
198
```javascript
199
{
200
chunkFilename: "[id].[contenthash].worker.js"
201
}
202
```
203
204
#### Inline Option
205
206
Enables inline worker mode using Blob URLs to avoid cross-origin issues.
207
208
```javascript
209
{
210
inline: "fallback" // Creates fallback file for unsupported browsers
211
}
212
```
213
214
```javascript
215
{
216
inline: "no-fallback" // Inline only, no fallback file
217
}
218
```
219
220
#### ESModule Option
221
222
Controls whether generated code uses ES modules or CommonJS syntax.
223
224
```javascript
225
{
226
esModule: false // Use CommonJS: module.exports = function...
227
}
228
```
229
230
### Cross-Origin Support
231
232
Handle cross-origin restrictions with inline workers.
233
234
```javascript { .api }
235
// Runtime inline worker function (from runtime/inline.js)
236
// Creates workers using Blob URLs with progressive fallback strategies
237
function inlineWorker(
238
content: string, // Worker source code content
239
workerConstructor: string, // Constructor name ("Worker", "SharedWorker", etc.)
240
workerOptions?: object, // Worker constructor options
241
url?: string // Fallback URL for unsupported environments
242
): Worker | SharedWorker
243
244
// Fallback strategy:
245
// 1. Try Blob API with URL.createObjectURL()
246
// 2. Try data: URL with encoded content
247
// 3. Fall back to external URL if provided
248
// 4. Throw error if no fallback available
249
```
250
251
**Usage with inline option:**
252
253
```javascript
254
// webpack.config.js
255
module.exports = {
256
module: {
257
rules: [
258
{
259
test: /\.worker\.js$/,
260
loader: "worker-loader",
261
options: {
262
inline: "fallback"
263
}
264
}
265
]
266
}
267
};
268
269
// Your application code remains the same
270
import Worker from "./file.worker.js";
271
const worker = new Worker();
272
```
273
274
### TypeScript Integration
275
276
For TypeScript projects, define custom module declarations.
277
278
```typescript { .api }
279
// typings/worker-loader.d.ts
280
declare module "worker-loader!*" {
281
class WebpackWorker extends Worker {
282
constructor();
283
}
284
export default WebpackWorker;
285
}
286
```
287
288
**TypeScript usage:**
289
290
```typescript
291
import Worker from "worker-loader!./Worker.ts";
292
293
const worker = new Worker();
294
worker.postMessage({ data: "Hello from TypeScript!" });
295
worker.onmessage = (event) => {
296
console.log("Worker response:", event.data);
297
};
298
```
299
300
### Generated Code Patterns
301
302
The loader generates different code patterns based on configuration:
303
304
#### Standard Worker Factory (esModule: true)
305
306
```javascript { .api }
307
export default function Worker_fn() {
308
return new Worker(__webpack_public_path__ + "worker.worker.js");
309
}
310
```
311
312
#### CommonJS Worker Factory (esModule: false)
313
314
```javascript { .api }
315
module.exports = function Worker_fn() {
316
return new Worker(__webpack_public_path__ + "worker.worker.js");
317
}
318
```
319
320
#### SharedWorker with Options
321
322
```javascript { .api }
323
export default function SharedWorker_fn() {
324
return new SharedWorker(
325
__webpack_public_path__ + "worker.worker.js",
326
{ "type": "classic", "name": "my-worker" }
327
);
328
}
329
```
330
331
#### Inline Worker Factory
332
333
```javascript { .api }
334
import worker from "!!./runtime/inline.js";
335
336
export default function Worker_fn() {
337
return worker(
338
/* worker source code */,
339
"Worker",
340
/* worker options */,
341
/* fallback url */
342
);
343
}
344
```
345
346
## Advanced Examples
347
348
### Babel Integration
349
350
For ES6+ features in workers, combine with babel-loader:
351
352
```javascript
353
module.exports = {
354
module: {
355
rules: [
356
{
357
test: /\.worker\.(c|m)?js$/i,
358
use: [
359
{
360
loader: "worker-loader"
361
},
362
{
363
loader: "babel-loader",
364
options: {
365
presets: ["@babel/preset-env"]
366
}
367
}
368
]
369
}
370
]
371
}
372
};
373
```
374
375
### Dynamic Worker Creation
376
377
Using function-based filename for dynamic naming:
378
379
```javascript
380
module.exports = {
381
module: {
382
rules: [
383
{
384
test: /\.worker\.js$/,
385
loader: "worker-loader",
386
options: {
387
filename: (pathData) => {
388
const workerName = pathData.chunk.entryModule.resource
389
.split("/")
390
.pop()
391
.replace(".worker.js", "");
392
return `workers/${workerName}.[contenthash].js`;
393
}
394
}
395
}
396
]
397
}
398
};
399
```
400
401
### WASM Worker Support
402
403
Worker Loader automatically handles WebAssembly modules in workers:
404
405
```javascript
406
// worker-with-wasm.worker.js
407
import wasmModule from "./calculator.wasm";
408
409
onmessage = async function(event) {
410
const wasm = await wasmModule();
411
const result = wasm.calculate(event.data.numbers);
412
postMessage({ result });
413
};
414
```
415
416
## Error Handling
417
418
Worker Loader handles various error scenarios:
419
420
1. **Browser Compatibility**: When `inline: "fallback"` is used, unsupported browsers fall back to external files
421
2. **Cross-Origin Issues**: Inline mode creates Blob URLs to bypass CORS restrictions
422
3. **Build Failures**: Invalid worker code causes webpack compilation errors with clear messages
423
4. **Runtime Errors**: Standard Web Worker error handling applies to generated workers
424
425
```javascript
426
const worker = new Worker();
427
428
worker.onerror = function(error) {
429
console.error("Worker error:", error);
430
};
431
432
worker.onmessageerror = function(error) {
433
console.error("Worker message error:", error);
434
};
435
```