0
# Service Worker Generation
1
2
The GenerateSW plugin automatically generates a complete service worker file with precaching and runtime caching configuration. It analyzes your webpack build output and creates an optimized service worker for Progressive Web App caching strategies.
3
4
## Capabilities
5
6
### GenerateSW Class
7
8
Creates a webpack plugin that generates a complete service worker file during the build process.
9
10
```typescript { .api }
11
/**
12
* Creates an instance of GenerateSW plugin
13
* @param config - Configuration options for service worker generation
14
*/
15
class GenerateSW {
16
constructor(config?: GenerateSWConfig);
17
18
/**
19
* Webpack plugin interface method - called by webpack during compilation
20
* @param compiler - Webpack compiler instance
21
*/
22
apply(compiler: webpack.Compiler): void;
23
}
24
25
interface GenerateSWConfig extends WebpackGenerateSWOptions {
26
manifestEntries?: Array<ManifestEntry>;
27
}
28
```
29
30
**Usage Examples:**
31
32
```typescript
33
import { GenerateSW } from "workbox-webpack-plugin";
34
35
// Basic configuration
36
new GenerateSW({
37
swDest: 'service-worker.js',
38
skipWaiting: true,
39
clientsClaim: true,
40
});
41
42
// Advanced configuration with runtime caching
43
new GenerateSW({
44
swDest: 'sw.js',
45
skipWaiting: true,
46
clientsClaim: true,
47
exclude: [/\.map$/, /manifest$/, /\.htaccess$/],
48
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024, // 5MB
49
runtimeCaching: [
50
{
51
urlPattern: /^https:\/\/fonts\.googleapis\.com/,
52
handler: 'StaleWhileRevalidate',
53
options: {
54
cacheName: 'google-fonts-stylesheets',
55
},
56
},
57
{
58
urlPattern: /^https:\/\/api\.example\.com\/users/,
59
handler: 'NetworkFirst',
60
options: {
61
cacheName: 'api-users',
62
expiration: {
63
maxEntries: 50,
64
maxAgeSeconds: 300, // 5 minutes
65
},
66
},
67
},
68
{
69
urlPattern: /\.(?:png|jpg|jpeg|svg|gif)$/,
70
handler: 'CacheFirst',
71
options: {
72
cacheName: 'images',
73
expiration: {
74
maxEntries: 60,
75
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days
76
},
77
},
78
},
79
],
80
navigateFallback: '/index.html',
81
navigateFallbackDenylist: [/^\/api\//, /^\/admin\//],
82
});
83
```
84
85
### Configuration Options
86
87
The GenerateSW plugin accepts all options from workbox-build's generateSW method, plus webpack-specific options.
88
89
```typescript { .api }
90
interface WebpackGenerateSWOptions {
91
/** Additional entries to include in the precache manifest */
92
additionalManifestEntries?: Array<ManifestEntry | string>;
93
94
/** Babel preset-env targets for service worker compilation */
95
babelPresetEnvTargets?: string[];
96
97
/** Cache ID prefix for all caches used by the service worker */
98
cacheId?: string;
99
100
/** Remove outdated caches during service worker activation */
101
cleanupOutdatedCaches?: boolean;
102
103
/** Service worker takes control of all clients immediately */
104
clientsClaim?: boolean;
105
106
/** Directory index file for navigation requests */
107
directoryIndex?: string;
108
109
/** Disable development logging in the generated service worker */
110
disableDevLogs?: boolean;
111
112
/** Files to exclude from precaching */
113
exclude?: Array<RegExp | string | ((asset: {name: string}) => boolean)>;
114
115
/** Webpack chunks to exclude from precaching */
116
excludeChunks?: Array<string>;
117
118
/** URL parameters to ignore when matching precached URLs */
119
ignoreURLParametersMatching?: Array<RegExp>;
120
121
/** Additional scripts to import into the service worker */
122
importScripts?: Array<string>;
123
124
/** Webpack chunks whose files should be imported into the service worker */
125
importScriptsViaChunks?: Array<string>;
126
127
/** Inline the Workbox runtime instead of importing it */
128
inlineWorkboxRuntime?: boolean;
129
130
/** Functions to transform the precache manifest */
131
manifestTransforms?: Array<ManifestTransform>;
132
133
/** Maximum file size (in bytes) to include in precache */
134
maximumFileSizeToCacheInBytes?: number;
135
136
/** Build mode - affects optimization and debugging */
137
mode?: 'development' | 'production';
138
139
/** URL to use for navigation fallback */
140
navigateFallback?: string;
141
142
/** URLs that should use navigation fallback */
143
navigateFallbackAllowlist?: Array<RegExp>;
144
145
/** URLs that should not use navigation fallback */
146
navigateFallbackDenylist?: Array<RegExp>;
147
148
/** Enable offline Google Analytics */
149
offlineGoogleAnalytics?: boolean | GoogleAnalyticsInitializeOptions;
150
151
/** Runtime caching strategies for different URL patterns */
152
runtimeCaching?: Array<RuntimeCachingEntry>;
153
154
/** Service worker skips waiting and activates immediately */
155
skipWaiting?: boolean;
156
157
/** Generate source maps for the service worker */
158
sourcemap?: boolean;
159
160
/** Output filename for the generated service worker */
161
swDest?: string;
162
}
163
```
164
165
### Runtime Caching Configuration
166
167
Configure caching strategies for different types of requests:
168
169
```typescript { .api }
170
interface RuntimeCachingEntry {
171
/** Caching strategy to use */
172
handler: 'CacheFirst' | 'CacheOnly' | 'NetworkFirst' | 'NetworkOnly' | 'StaleWhileRevalidate';
173
174
/** Pattern to match URLs against */
175
urlPattern: RegExp | string | ((params: {request: Request, url: URL}) => boolean);
176
177
/** HTTP method to match (defaults to GET) */
178
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'PATCH';
179
180
/** Additional options for the caching strategy */
181
options?: {
182
/** Background sync configuration */
183
backgroundSync?: {
184
name: string;
185
options?: BackgroundSyncOptions;
186
};
187
188
/** Broadcast update configuration */
189
broadcastUpdate?: {
190
channelName?: string;
191
options?: BroadcastChannelOptions;
192
};
193
194
/** Response caching criteria */
195
cacheableResponse?: {
196
statuses?: Array<number>;
197
headers?: Record<string, string>;
198
};
199
200
/** Cache name for this strategy */
201
cacheName?: string;
202
203
/** Cache expiration settings */
204
expiration?: {
205
maxEntries?: number;
206
maxAgeSeconds?: number;
207
};
208
209
/** Network timeout in seconds */
210
networkTimeoutSeconds?: number;
211
212
/** Workbox plugins to apply */
213
plugins?: Array<any>;
214
215
/** Fallback configuration for precached resources */
216
precacheFallback?: {
217
fallbackURL: string;
218
};
219
};
220
}
221
```
222
223
**Common Runtime Caching Patterns:**
224
225
```typescript
226
// Cache Google Fonts
227
{
228
urlPattern: /^https:\/\/fonts\.googleapis\.com/,
229
handler: 'StaleWhileRevalidate',
230
options: {
231
cacheName: 'google-fonts-stylesheets',
232
},
233
}
234
235
// Cache API responses with network priority
236
{
237
urlPattern: /^https:\/\/api\.example\.com/,
238
handler: 'NetworkFirst',
239
options: {
240
cacheName: 'api-cache',
241
networkTimeoutSeconds: 3,
242
expiration: {
243
maxEntries: 50,
244
maxAgeSeconds: 5 * 60, // 5 minutes
245
},
246
},
247
}
248
249
// Cache images with cache priority
250
{
251
urlPattern: /\.(?:png|jpg|jpeg|svg|gif|webp)$/,
252
handler: 'CacheFirst',
253
options: {
254
cacheName: 'images',
255
expiration: {
256
maxEntries: 100,
257
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days
258
},
259
},
260
}
261
```