0
# Workbox Webpack Plugin
1
2
Workbox Webpack Plugin provides Webpack plugins that integrate Workbox functionality into Webpack builds, enabling automatic generation of service worker precache manifests and configurations. It helps developers implement Progressive Web App (PWA) caching strategies by automatically analyzing build outputs and generating optimized precache lists for static assets.
3
4
## Package Information
5
6
- **Package Name**: workbox-webpack-plugin
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install workbox-webpack-plugin`
10
11
## Core Imports
12
13
```typescript
14
import { GenerateSW, GenerateSWConfig, InjectManifest } from "workbox-webpack-plugin";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { GenerateSW, GenerateSWConfig, InjectManifest } = require("workbox-webpack-plugin");
21
```
22
23
Default export (for backward compatibility):
24
25
```typescript
26
import WorkboxPlugin from "workbox-webpack-plugin";
27
const { GenerateSW, InjectManifest } = WorkboxPlugin;
28
```
29
30
## Basic Usage
31
32
```typescript
33
import { GenerateSW, InjectManifest } from "workbox-webpack-plugin";
34
35
// Generate complete service worker
36
module.exports = {
37
// ... webpack config
38
plugins: [
39
new GenerateSW({
40
swDest: 'sw.js',
41
skipWaiting: true,
42
clientsClaim: true,
43
runtimeCaching: [{
44
urlPattern: /^https:\/\/api\.example\.com/,
45
handler: 'NetworkFirst',
46
options: {
47
cacheName: 'api-cache',
48
},
49
}],
50
}),
51
],
52
};
53
54
// Inject manifest into existing service worker
55
module.exports = {
56
// ... webpack config
57
plugins: [
58
new InjectManifest({
59
swSrc: './src/sw.js',
60
swDest: 'sw.js',
61
}),
62
],
63
};
64
```
65
66
## Architecture
67
68
Workbox Webpack Plugin consists of two main components:
69
70
- **GenerateSW Plugin**: Automatically generates a complete service worker file with precaching and runtime caching configuration
71
- **InjectManifest Plugin**: Takes an existing service worker and injects a precache manifest based on webpack assets
72
- **Asset Analysis**: Automatically discovers and processes webpack compilation assets to create precache manifests
73
- **Webpack Integration**: Hooks into webpack's compilation process using appropriate lifecycle events for v4/v5 compatibility
74
75
## Capabilities
76
77
### Service Worker Generation
78
79
Complete service worker generation with automatic precaching and customizable runtime caching strategies.
80
81
```typescript { .api }
82
class GenerateSW {
83
/**
84
* Creates an instance of GenerateSW plugin
85
* @param config - Configuration options for service worker generation
86
*/
87
constructor(config?: GenerateSWConfig);
88
89
/**
90
* Webpack plugin interface method - called by webpack during compilation
91
* @param compiler - Webpack compiler instance
92
*/
93
apply(compiler: webpack.Compiler): void;
94
}
95
96
interface GenerateSWConfig extends WebpackGenerateSWOptions {
97
/** Optional array of additional manifest entries to include in precache */
98
manifestEntries?: Array<ManifestEntry>;
99
}
100
```
101
102
[Service Worker Generation](./generate-sw.md)
103
104
### Manifest Injection
105
106
Inject precache manifest into existing service worker source files with webpack compilation support.
107
108
```typescript { .api }
109
class InjectManifest {
110
/**
111
* Creates an instance of InjectManifest plugin
112
* @param config - Configuration options for manifest injection
113
*/
114
constructor(config: WebpackInjectManifestOptions);
115
116
/**
117
* Webpack plugin interface method - called by webpack during compilation
118
* @param compiler - Webpack compiler instance
119
*/
120
apply(compiler: webpack.Compiler): void;
121
}
122
```
123
124
[Manifest Injection](./inject-manifest.md)
125
126
## Types
127
128
```typescript { .api }
129
interface ManifestEntry {
130
/** The URL of the asset to precache */
131
url: string;
132
/** The revision hash for cache busting, or null for unversioned assets */
133
revision: string | null;
134
}
135
136
interface WebpackGenerateSWOptions {
137
additionalManifestEntries?: Array<ManifestEntry | string>;
138
babelPresetEnvTargets?: string[];
139
cacheId?: string;
140
cleanupOutdatedCaches?: boolean;
141
clientsClaim?: boolean;
142
directoryIndex?: string;
143
disableDevLogs?: boolean;
144
exclude?: Array<RegExp | string | ((asset: {name: string}) => boolean)>;
145
excludeChunks?: Array<string>;
146
ignoreURLParametersMatching?: Array<RegExp>;
147
importScripts?: Array<string>;
148
importScriptsViaChunks?: Array<string>;
149
inlineWorkboxRuntime?: boolean;
150
manifestTransforms?: Array<ManifestTransform>;
151
maximumFileSizeToCacheInBytes?: number;
152
mode?: 'development' | 'production';
153
navigateFallback?: string;
154
navigateFallbackAllowlist?: Array<RegExp>;
155
navigateFallbackDenylist?: Array<RegExp>;
156
offlineGoogleAnalytics?: boolean | GoogleAnalyticsInitializeOptions;
157
runtimeCaching?: Array<RuntimeCachingEntry>;
158
skipWaiting?: boolean;
159
sourcemap?: boolean;
160
swDest?: string;
161
}
162
163
interface WebpackInjectManifestOptions {
164
additionalManifestEntries?: Array<ManifestEntry | string>;
165
compileSrc?: boolean;
166
exclude?: Array<RegExp | string | ((asset: {name: string}) => boolean)>;
167
excludeChunks?: Array<string>;
168
ignoreURLParametersMatching?: Array<RegExp>;
169
injectionPoint?: string;
170
manifestTransforms?: Array<ManifestTransform>;
171
maximumFileSizeToCacheInBytes?: number;
172
mode?: 'development' | 'production';
173
swDest?: string;
174
swSrc: string;
175
webpackCompilationPlugins?: Array<any>;
176
}
177
178
interface RuntimeCachingEntry {
179
handler: 'CacheFirst' | 'CacheOnly' | 'NetworkFirst' | 'NetworkOnly' | 'StaleWhileRevalidate';
180
urlPattern: RegExp | string | ((params: {request: Request, url: URL}) => boolean);
181
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'PATCH';
182
options?: {
183
backgroundSync?: {
184
name: string;
185
options?: BackgroundSyncOptions;
186
};
187
broadcastUpdate?: {
188
channelName?: string;
189
options?: BroadcastChannelOptions;
190
};
191
cacheableResponse?: {
192
statuses?: Array<number>;
193
headers?: Record<string, string>;
194
};
195
cacheName?: string;
196
expiration?: {
197
maxEntries?: number;
198
maxAgeSeconds?: number;
199
};
200
networkTimeoutSeconds?: number;
201
plugins?: Array<any>;
202
precacheFallback?: {
203
fallbackURL: string;
204
};
205
};
206
}
207
208
interface ManifestTransform {
209
(originalManifest: Array<ManifestEntry>, compilation?: webpack.Compilation): Promise<{
210
manifest: Array<ManifestEntry>;
211
warnings?: Array<string>;
212
}> | {
213
manifest: Array<ManifestEntry>;
214
warnings?: Array<string>;
215
};
216
}
217
```