0
# Service Worker Management
1
2
Service worker generation for production builds using Workbox webpack plugin integration, and development middleware that serves no-op service workers to prevent caching issues during development.
3
4
## Capabilities
5
6
### Development Middleware
7
8
Creates Express middleware that serves a no-op service worker during development to prevent production service worker caching issues.
9
10
```javascript { .api }
11
/**
12
* Creates development middleware for serving no-op service worker
13
* @returns {Function} Express middleware function that intercepts /service-worker.js requests
14
*/
15
function createNoopServiceWorkerMiddleware(): (req: Request, res: Response, next: NextFunction) => void;
16
```
17
18
**Usage Example:**
19
20
```javascript
21
const createNoopServiceWorkerMiddleware = require('@vue/cli-plugin-pwa/lib/noopServiceWorkerMiddleware');
22
const express = require('express');
23
24
const app = express();
25
app.use(createNoopServiceWorkerMiddleware());
26
27
// When accessing /service-worker.js in development, serves the no-op service worker
28
```
29
30
### No-op Service Worker Script
31
32
The actual service worker script served during development that resets any existing service workers.
33
34
```javascript { .api }
35
// Development service worker content
36
self.addEventListener('install', () => self.skipWaiting());
37
self.addEventListener('fetch', () => {});
38
self.addEventListener('activate', () => {
39
self.clients.matchAll({ type: 'window' }).then(windowClients => {
40
for (const windowClient of windowClients) {
41
windowClient.navigate(windowClient.url);
42
}
43
});
44
});
45
```
46
47
### Production Service Worker Generation
48
49
In production builds, the plugin integrates with Workbox webpack plugin to generate actual service workers with precaching capabilities.
50
51
```javascript { .api }
52
/**
53
* Workbox plugin integration for production service worker generation
54
* Applied automatically when NODE_ENV === 'production'
55
*/
56
interface WorkboxIntegration {
57
/** Plugin mode: 'GenerateSW' (default) or 'InjectManifest' */
58
workboxPluginMode: 'GenerateSW' | 'InjectManifest';
59
/** Configuration passed to Workbox webpack plugin */
60
workboxOptions: WorkboxOptions;
61
}
62
```
63
64
### Workbox Plugin Modes
65
66
Two service worker generation strategies provided by Workbox.
67
68
```javascript { .api }
69
/**
70
* GenerateSW Mode - Automatically generates complete service worker
71
* Best for: Simple PWAs with standard caching needs
72
*/
73
interface GenerateSWMode {
74
mode: 'GenerateSW';
75
options: {
76
/** Cache identifier for service worker */
77
cacheId?: string;
78
/** Files to exclude from precaching */
79
exclude?: RegExp[];
80
/** Whether to skip waiting during service worker updates */
81
skipWaiting?: boolean;
82
/** Whether to claim clients immediately */
83
clientsClaim?: boolean;
84
/** Runtime caching strategies */
85
runtimeCaching?: RuntimeCachingEntry[];
86
};
87
}
88
89
/**
90
* InjectManifest Mode - Injects precache manifest into existing service worker
91
* Best for: Custom service worker logic with precaching
92
*/
93
interface InjectManifestMode {
94
mode: 'InjectManifest';
95
options: {
96
/** Path to source service worker file */
97
swSrc: string;
98
/** Files to exclude from precaching */
99
exclude?: RegExp[];
100
/** Additional Workbox options */
101
[key: string]: any;
102
};
103
}
104
```
105
106
### Runtime Caching Configuration
107
108
Configuration for caching strategies applied to runtime requests.
109
110
```javascript { .api }
111
interface RuntimeCachingEntry {
112
/** URL pattern to match for caching */
113
urlPattern: RegExp | string;
114
/** Caching strategy handler */
115
handler: 'CacheFirst' | 'NetworkFirst' | 'NetworkOnly' | 'CacheOnly' | 'StaleWhileRevalidate';
116
/** Additional caching options */
117
options?: {
118
/** Custom cache name */
119
cacheName?: string;
120
/** Network timeout for NetworkFirst strategy */
121
networkTimeoutSeconds?: number;
122
/** Cache expiration settings */
123
expiration?: {
124
maxEntries?: number;
125
maxAgeSeconds?: number;
126
};
127
/** Background sync settings */
128
backgroundSync?: {
129
name: string;
130
options?: any;
131
};
132
};
133
}
134
```
135
136
**Usage Examples:**
137
138
```javascript
139
// GenerateSW mode with runtime caching
140
module.exports = {
141
pwa: {
142
workboxPluginMode: 'GenerateSW',
143
workboxOptions: {
144
skipWaiting: true,
145
clientsClaim: true,
146
runtimeCaching: [
147
{
148
urlPattern: /^https:\/\/api\.example\.com\//,
149
handler: 'NetworkFirst',
150
options: {
151
cacheName: 'api-cache',
152
networkTimeoutSeconds: 3,
153
expiration: {
154
maxEntries: 50,
155
maxAgeSeconds: 300 // 5 minutes
156
}
157
}
158
},
159
{
160
urlPattern: /\.(?:png|jpg|jpeg|svg)$/,
161
handler: 'CacheFirst',
162
options: {
163
cacheName: 'images',
164
expiration: {
165
maxEntries: 100,
166
maxAgeSeconds: 86400 // 24 hours
167
}
168
}
169
}
170
]
171
}
172
}
173
};
174
```
175
176
```javascript
177
// InjectManifest mode with custom service worker
178
module.exports = {
179
pwa: {
180
workboxPluginMode: 'InjectManifest',
181
workboxOptions: {
182
swSrc: 'src/sw.js',
183
exclude: [/\.map$/, /manifest$/, /\.htaccess$/]
184
}
185
}
186
};
187
188
// src/sw.js - Custom service worker
189
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
190
import { registerRoute } from 'workbox-routing';
191
import { StaleWhileRevalidate } from 'workbox-strategies';
192
193
// Precache and route static assets
194
precacheAndRoute(self.__WB_MANIFEST);
195
cleanupOutdatedCaches();
196
197
// Custom runtime caching
198
registerRoute(
199
({ request }) => request.destination === 'document',
200
new StaleWhileRevalidate({
201
cacheName: 'pages-cache'
202
})
203
);
204
```
205
206
### Default Exclusions
207
208
Files excluded from precaching by default.
209
210
```javascript { .api }
211
const defaultExclusions = [
212
/\.map$/, // Source maps
213
/img\/icons\//, // PWA icons (served separately)
214
/favicon\.ico$/, // Favicon
215
/^manifest.*\.js?$/ // Manifest files
216
];
217
```
218
219
### Service Worker Validation
220
221
The plugin validates Workbox plugin mode against available options.
222
223
```javascript { .api }
224
/**
225
* Validates workboxPluginMode against available Workbox webpack plugin modes
226
* @param {string} mode - The specified workbox plugin mode
227
* @throws {Error} When mode is not supported
228
*/
229
if (!(workboxPluginMode in workboxWebpackModule)) {
230
throw new Error(
231
`${workboxPluginMode} is not a supported Workbox webpack plugin mode. ` +
232
`Valid modes are: ${Object.keys(workboxWebpackModule).join(', ')}`
233
);
234
}
235
```
236
237
### Client Service Worker Registration
238
239
Template for registering service workers in the client application.
240
241
```javascript { .api }
242
// Generated registerServiceWorker.js template
243
import { register } from 'register-service-worker';
244
245
if (process.env.NODE_ENV === 'production') {
246
register(`${process.env.BASE_URL}service-worker.js`, {
247
ready() {
248
console.log('App is being served from cache by a service worker.');
249
},
250
registered() {
251
console.log('Service worker has been registered.');
252
},
253
cached() {
254
console.log('Content has been cached for offline use.');
255
},
256
updatefound() {
257
console.log('New content is downloading.');
258
},
259
updated() {
260
console.log('New content is available; please refresh.');
261
},
262
offline() {
263
console.log('No internet connection found. App is running in offline mode.');
264
},
265
error(error) {
266
console.error('Error during service worker registration:', error);
267
}
268
});
269
}
270
```