0
# Manifest Injection
1
2
The InjectManifest plugin takes an existing service worker source file and injects a precache manifest based on webpack assets. This allows you to write custom service worker logic while still benefiting from automatic asset precaching.
3
4
## Capabilities
5
6
### InjectManifest Class
7
8
Creates a webpack plugin that compiles an existing service worker and injects a precache manifest into it.
9
10
```typescript { .api }
11
/**
12
* Creates an instance of InjectManifest plugin
13
* @param config - Configuration options for manifest injection
14
*/
15
class InjectManifest {
16
constructor(config: WebpackInjectManifestOptions);
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
26
**Usage Examples:**
27
28
```typescript
29
import { InjectManifest } from "workbox-webpack-plugin";
30
31
// Basic configuration
32
new InjectManifest({
33
swSrc: './src/service-worker.js',
34
swDest: 'sw.js',
35
});
36
37
// Advanced configuration with compilation options
38
new InjectManifest({
39
swSrc: './src/sw.ts', // TypeScript source
40
swDest: 'service-worker.js',
41
compileSrc: true,
42
exclude: [/\.map$/, /manifest$/],
43
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
44
webpackCompilationPlugins: [
45
// Additional webpack plugins for service worker compilation
46
],
47
});
48
```
49
50
### Source Service Worker Setup
51
52
Your source service worker file must include an injection point where the manifest will be inserted:
53
54
```javascript
55
// src/service-worker.js
56
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
57
import { registerRoute } from 'workbox-routing';
58
import { CacheFirst } from 'workbox-strategies';
59
60
// This will be replaced with the actual precache manifest
61
precacheAndRoute(self.__WB_MANIFEST);
62
63
// Optional: clean up outdated caches
64
cleanupOutdatedCaches();
65
66
// Add custom caching logic
67
registerRoute(
68
({ request }) => request.destination === 'image',
69
new CacheFirst({
70
cacheName: 'images',
71
plugins: [{
72
cacheKeyWillBeUsed: async ({ request }) => {
73
return `${request.url}?version=1`;
74
},
75
}],
76
})
77
);
78
79
// Custom event listeners
80
self.addEventListener('message', (event) => {
81
if (event.data && event.data.type === 'SKIP_WAITING') {
82
self.skipWaiting();
83
}
84
});
85
```
86
87
### Configuration Options
88
89
```typescript { .api }
90
interface WebpackInjectManifestOptions {
91
/** Additional entries to include in the precache manifest */
92
additionalManifestEntries?: Array<ManifestEntry | string>;
93
94
/** Whether to compile the service worker source through webpack */
95
compileSrc?: boolean;
96
97
/** Files to exclude from precaching */
98
exclude?: Array<RegExp | string | ((asset: {name: string}) => boolean)>;
99
100
/** Webpack chunks to exclude from precaching */
101
excludeChunks?: Array<string>;
102
103
/** URL parameters to ignore when matching precached URLs */
104
ignoreURLParametersMatching?: Array<RegExp>;
105
106
/** String to replace with the precache manifest (defaults to 'self.__WB_MANIFEST') */
107
injectionPoint?: string;
108
109
/** Functions to transform the precache manifest */
110
manifestTransforms?: Array<ManifestTransform>;
111
112
/** Maximum file size (in bytes) to include in precache */
113
maximumFileSizeToCacheInBytes?: number;
114
115
/** Build mode - affects optimization and debugging */
116
mode?: 'development' | 'production';
117
118
/** Output filename for the compiled service worker */
119
swDest?: string;
120
121
/** Path to the source service worker file */
122
swSrc: string;
123
124
/** Additional webpack plugins to apply during service worker compilation */
125
webpackCompilationPlugins?: Array<any>;
126
}
127
```
128
129
### Injection Point Customization
130
131
By default, the plugin looks for `self.__WB_MANIFEST` in your service worker source and replaces it with the actual precache manifest. You can customize this:
132
133
```typescript
134
new InjectManifest({
135
swSrc: './src/sw.js',
136
injectionPoint: 'MY_CUSTOM_MANIFEST',
137
});
138
```
139
140
Then in your service worker:
141
142
```javascript
143
// src/sw.js
144
import { precacheAndRoute } from 'workbox-precaching';
145
146
// Use custom injection point
147
precacheAndRoute(MY_CUSTOM_MANIFEST);
148
```
149
150
### TypeScript Service Workers
151
152
When using TypeScript for your service worker, enable compilation:
153
154
```typescript
155
new InjectManifest({
156
swSrc: './src/service-worker.ts',
157
swDest: 'sw.js',
158
compileSrc: true, // Enable TypeScript compilation
159
webpackCompilationPlugins: [
160
// Add any additional plugins needed for TS compilation
161
],
162
});
163
```
164
165
Your TypeScript service worker:
166
167
```typescript
168
// src/service-worker.ts
169
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
170
import { registerRoute, NavigationRoute } from 'workbox-routing';
171
import { NetworkFirst } from 'workbox-strategies';
172
173
declare const self: ServiceWorkerGlobalScope;
174
175
// Precache and route static assets
176
precacheAndRoute(self.__WB_MANIFEST);
177
cleanupOutdatedCaches();
178
179
// Handle navigation requests
180
const navigationRoute = new NavigationRoute(
181
new NetworkFirst({
182
cacheName: 'navigations',
183
})
184
);
185
registerRoute(navigationRoute);
186
187
// Type-safe event handling
188
self.addEventListener('message', (event: ExtendableMessageEvent) => {
189
if (event.data?.type === 'SKIP_WAITING') {
190
self.skipWaiting();
191
}
192
});
193
```
194
195
### Manifest Transform Functions
196
197
Transform the generated manifest before injection:
198
199
```typescript { .api }
200
interface ManifestTransform {
201
(originalManifest: Array<ManifestEntry>, compilation?: webpack.Compilation): Promise<{
202
manifest: Array<ManifestEntry>;
203
warnings?: Array<string>;
204
}> | {
205
manifest: Array<ManifestEntry>;
206
warnings?: Array<string>;
207
};
208
}
209
210
interface ManifestEntry {
211
url: string;
212
revision: string | null;
213
}
214
```
215
216
**Example manifest transform:**
217
218
```typescript
219
const customTransform = (originalManifest, compilation) => {
220
// Add cache busting parameter to all URLs
221
const manifest = originalManifest.map(entry => ({
222
...entry,
223
url: `${entry.url}?v=${Date.now()}`,
224
}));
225
226
return { manifest };
227
};
228
229
new InjectManifest({
230
swSrc: './src/sw.js',
231
manifestTransforms: [customTransform],
232
});
233
```
234
235
### Webpack Compilation Integration
236
237
The plugin integrates with webpack's compilation process and handles both webpack 4 and 5:
238
239
- **Development Mode**: Provides detailed logging and faster builds
240
- **Production Mode**: Optimizes the service worker for smaller bundle size
241
- **Source Maps**: Automatically handled when `compileSrc` is enabled
242
- **Watch Mode**: Properly handles file dependencies and rebuilds