0
# SW Precache Webpack Plugin
1
2
SW Precache Webpack Plugin is a webpack plugin that generates service worker files using Google's sw-precache library. It automatically creates service workers that precache static assets, handle offline functionality, and manage cache invalidation for webpack-based applications.
3
4
## Package Information
5
6
- **Package Name**: sw-precache-webpack-plugin
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install --save-dev sw-precache-webpack-plugin`
10
- **Peer Dependencies**: webpack ^1 || ^2 || ^2.1.0-beta || ^2.2.0-beta || ^3 || ^4
11
12
## Core Imports
13
14
```javascript
15
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
16
```
17
18
For ES6+ environments (when webpack supports ES modules in config):
19
20
```javascript
21
import SWPrecacheWebpackPlugin from 'sw-precache-webpack-plugin';
22
```
23
24
Note: The plugin source uses ES6 imports internally but exports CommonJS for compatibility.
25
26
## Basic Usage
27
28
```javascript
29
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
30
31
module.exports = {
32
entry: './src/index.js',
33
34
plugins: [
35
// Simplest usage - uses webpack assets automatically
36
new SWPrecacheWebpackPlugin(),
37
38
// With configuration
39
new SWPrecacheWebpackPlugin({
40
cacheId: 'my-app-cache',
41
filename: 'service-worker.js',
42
minify: true,
43
staticFileGlobsIgnorePatterns: [/\.map$/]
44
})
45
]
46
};
47
```
48
49
## Architecture
50
51
SW Precache Webpack Plugin integrates with webpack's compilation process:
52
53
- **Plugin Lifecycle**: Hooks into webpack's `after-emit` event to ensure assets are available
54
- **Asset Discovery**: Automatically discovers webpack-generated assets for caching
55
- **Service Worker Generation**: Uses sw-precache library to generate optimized service worker code
56
- **File System Integration**: Writes service worker files using webpack's output file system
57
- **Configuration Merging**: Combines plugin options with sw-precache options for flexibility
58
59
## Capabilities
60
61
### Plugin Constructor
62
63
Creates a new instance of the webpack plugin for service worker generation.
64
65
```javascript { .api }
66
/**
67
* SWPrecacheWebpackPlugin - A wrapper for sw-precache to use with webpack
68
* @constructor
69
* @param {Object} options - All parameters should be passed as a single options object. All sw-precache options can be passed here in addition to plugin options.
70
*
71
* // plugin options:
72
* @param {string} [options.filename] - Service worker filename, default is 'service-worker.js'
73
* @param {string} [options.filepath] - Service worker path and name, default is to use webpack.output.path + options.filename
74
* @param {RegExp[]} [options.staticFileGlobsIgnorePatterns] - Define an optional array of regex patterns to filter out of staticFileGlobs
75
* @param {boolean} [options.mergeStaticsConfig=false] - Merge provided staticFileGlobs and stripPrefix(Multi) with webpack's config, rather than having those take precedence
76
* @param {boolean} [options.minify=false] - Minify the generated Service worker file using UglifyJS
77
* @param {boolean} [options.debug=false] - Output error and warning messages
78
* @returns {SWPrecacheWebpackPlugin} Plugin instance for webpack
79
*/
80
function SWPrecacheWebpackPlugin(options);
81
```
82
83
### Default Options and Constants
84
85
The plugin uses several default values and constants defined internally.
86
87
```javascript { .api }
88
/**
89
* Default configuration options applied when no user options are provided
90
*/
91
const DEFAULT_OPTIONS = {
92
cacheId: 'sw-precache-webpack-plugin',
93
filename: 'service-worker.js',
94
importScripts: [],
95
staticFileGlobsIgnorePatterns: [],
96
mergeStaticsConfig: false,
97
minify: false,
98
};
99
100
/**
101
* Default values used internally
102
*/
103
const DEFAULT_CACHE_ID = 'sw-precache-webpack-plugin';
104
const DEFAULT_WORKER_FILENAME = 'service-worker.js';
105
const DEFAULT_PUBLIC_PATH = '';
106
const DEFAULT_IMPORT_SCRIPTS = [];
107
const DEFAULT_IGNORE_PATTERNS = [];
108
```
109
110
### Plugin Configuration Options
111
112
```javascript { .api }
113
interface PluginOptions {
114
// Plugin-specific options
115
filename?: string; // Service worker filename (default: 'service-worker.js')
116
filepath?: string; // Complete service worker path (overrides filename)
117
staticFileGlobsIgnorePatterns?: RegExp[]; // Patterns to exclude from caching
118
mergeStaticsConfig?: boolean; // Merge provided globs with webpack config (default: false)
119
minify?: boolean; // Minify generated service worker (default: false)
120
121
// sw-precache options (all supported)
122
cacheId?: string; // Unique cache identifier (default: 'sw-precache-webpack-plugin')
123
importScripts?: (string | ImportScriptOptions)[]; // Scripts to import in service worker
124
staticFileGlobs?: string[]; // File patterns to cache
125
stripPrefix?: string; // Path prefix to strip from cache entries
126
stripPrefixMulti?: Record<string, string>; // Multiple prefix replacement rules
127
replacePrefix?: string; // Prefix replacement for URLs
128
navigateFallback?: string; // Fallback URL for navigation requests
129
navigateFallbackWhitelist?: RegExp[]; // Whitelist patterns for fallback
130
dontCacheBustUrlsMatching?: RegExp; // URLs to skip cache busting
131
skipWaiting?: boolean; // Skip waiting phase of service worker
132
clientsClaim?: boolean; // Take control of clients immediately
133
runtimeCaching?: RuntimeCacheRule[]; // Runtime caching strategies
134
handleFetch?: boolean; // Enable/disable fetch event handling
135
maximumFileSizeToCacheInBytes?: number; // Maximum file size to cache
136
directoryIndex?: string; // Directory index file
137
ignoreUrlParametersMatching?: RegExp[]; // URL parameters to ignore
138
verbose?: boolean; // Enable verbose logging
139
debug?: boolean; // Enable debug warnings
140
}
141
142
interface ImportScriptOptions {
143
filename?: string; // Script filename (supports [hash] placeholder)
144
chunkName?: string; // Webpack chunk name (overrides filename)
145
}
146
147
interface RuntimeCacheRule {
148
urlPattern: string | RegExp; // URL pattern to match
149
handler: 'cacheFirst' | 'networkFirst' | 'fastest' | 'cacheOnly' | 'networkOnly';
150
options?: {
151
cache?: {
152
name: string; // Cache name
153
maxEntries?: number; // Maximum cache entries
154
maxAgeSeconds?: number; // Maximum age in seconds
155
};
156
networkTimeoutSeconds?: number; // Network timeout
157
};
158
}
159
```
160
161
### Plugin Properties and Methods
162
163
The plugin exposes internal properties and methods for configuration and webpack integration.
164
165
```javascript { .api }
166
/**
167
* Returns merged configuration options for sw-precache
168
* @returns {Object} Combined options from config, user options, and overrides
169
*/
170
get workerOptions();
171
172
/**
173
* Main webpack plugin method called by webpack compiler
174
* @param {Object} compiler - Webpack compiler instance
175
*/
176
apply(compiler);
177
178
/**
179
* Configures service worker options based on webpack compilation data
180
* @param {Object} compiler - Webpack compiler instance
181
* @param {Object} compilation - Webpack compilation object
182
* @returns {void}
183
*/
184
configure(compiler, compilation);
185
186
/**
187
* Processes importScripts configuration with hash replacement and chunk resolution
188
* @param {Array} importScripts - Array of script configurations
189
* @param {string} publicPath - Webpack public path
190
* @param {Object} compiler - Webpack compiler instance
191
* @param {Object} compilation - Webpack compilation object
192
* @returns {void}
193
*/
194
configureImportScripts(importScripts, publicPath, compiler, compilation);
195
196
/**
197
* Validates configuration and pushes warnings to webpack compilation
198
* @param {Object} compilation - Webpack compilation object
199
* @returns {void}
200
*/
201
checkWarnings(compilation);
202
```
203
204
### Service Worker Generation
205
206
The plugin generates service worker content using the sw-precache library with webpack asset integration.
207
208
```javascript { .api }
209
/**
210
* Generates service worker content using sw-precache
211
* @returns {Promise<string>} Generated service worker code
212
*/
213
createServiceWorker();
214
215
/**
216
* Writes service worker file to the output file system
217
* @param {string} serviceWorker - Generated service worker content
218
* @param {Object} compiler - Webpack compiler instance
219
* @returns {Promise<void>} Promise resolving when file is written
220
*/
221
writeServiceWorker(serviceWorker, compiler);
222
```
223
224
## Usage Examples
225
226
### Simple Configuration
227
228
```javascript
229
const path = require('path');
230
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
231
232
module.exports = {
233
entry: './src/index.js',
234
output: {
235
path: path.resolve(__dirname, 'dist'),
236
filename: 'bundle.js',
237
publicPath: '/'
238
},
239
plugins: [
240
new SWPrecacheWebpackPlugin({
241
cacheId: 'my-project',
242
filename: 'sw.js',
243
minify: true
244
})
245
]
246
};
247
```
248
249
### Advanced Configuration with Static Files
250
251
```javascript
252
const path = require('path');
253
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
254
255
module.exports = {
256
entry: './src/index.js',
257
output: {
258
path: path.resolve(__dirname, 'dist'),
259
filename: '[name]-[hash].js',
260
publicPath: 'https://example.com/assets/'
261
},
262
plugins: [
263
new SWPrecacheWebpackPlugin({
264
cacheId: 'my-project-cache',
265
filename: 'service-worker.js',
266
staticFileGlobs: [
267
'public/images/**/*',
268
'public/fonts/**/*'
269
],
270
stripPrefix: 'public/',
271
mergeStaticsConfig: true,
272
staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
273
navigateFallback: '/index.html',
274
navigateFallbackWhitelist: [/^(?!\/__).*/],
275
minify: true
276
})
277
]
278
};
279
```
280
281
This generates a service worker at `dist/service-worker.js` that caches webpack assets plus additional static files.
282
283
### Service Worker Registration
284
285
After the plugin generates the service worker file, you need to register it in your application:
286
287
```javascript
288
// Register the service worker (client-side code)
289
if ('serviceWorker' in navigator) {
290
window.addEventListener('load', () => {
291
navigator.serviceWorker.register('/service-worker.js')
292
.then(registration => {
293
console.log('SW registered:', registration);
294
})
295
.catch(registrationError => {
296
console.log('SW registration failed:', registrationError);
297
});
298
});
299
}
300
```
301
302
### Runtime Caching Configuration
303
304
```javascript
305
new SWPrecacheWebpackPlugin({
306
cacheId: 'my-app',
307
runtimeCaching: [
308
{
309
urlPattern: /^https:\/\/api\.example\.com\//,
310
handler: 'networkFirst',
311
options: {
312
cache: {
313
name: 'api-cache',
314
maxEntries: 50,
315
maxAgeSeconds: 300
316
}
317
}
318
},
319
{
320
urlPattern: /\.(?:png|jpg|jpeg|svg)$/,
321
handler: 'cacheFirst',
322
options: {
323
cache: {
324
name: 'image-cache',
325
maxEntries: 100,
326
maxAgeSeconds: 86400
327
}
328
}
329
}
330
]
331
})
332
```
333
334
### Import Scripts with Hash Support
335
336
```javascript
337
new SWPrecacheWebpackPlugin({
338
cacheId: 'my-app',
339
importScripts: [
340
{
341
filename: 'sw-toolbox-[hash].js' // [hash] gets replaced with webpack compilation hash
342
},
343
{
344
chunkName: 'sw-runtime' // Uses webpack chunk by name
345
}
346
]
347
})
348
```
349
350
### Multiple Service Workers
351
352
```javascript
353
// Generate separate service workers for different entry points
354
module.exports = {
355
entry: {
356
home: './src/home/index.js',
357
admin: './src/admin/index.js'
358
},
359
360
plugins: [
361
new SWPrecacheWebpackPlugin({
362
cacheId: 'home-cache',
363
filename: 'home-sw.js',
364
staticFileGlobs: ['dist/home-*.js', 'dist/home-*.css']
365
}),
366
new SWPrecacheWebpackPlugin({
367
cacheId: 'admin-cache',
368
filename: 'admin-sw.js',
369
staticFileGlobs: ['dist/admin-*.js', 'dist/admin-*.css']
370
})
371
]
372
};
373
```
374
375
## Error Handling
376
377
The plugin provides warning messages for common configuration issues:
378
379
```javascript { .api }
380
// Error and Warning Constants
381
const CHUNK_NAME_NOT_FOUND_ERROR = 'Could not locate files for chunkName: "%s"';
382
const CHUNK_NAME_OVERRIDES_FILENAME_WARNING = 'Don\'t use chunkName & filename together; importScripts[<index>].filename overriden by specified chunkName: %j';
383
const FILEPATH_WARNING = 'sw-prechache-webpack-plugin [filepath]: You are using a custom path for your service worker, this may prevent the service worker from working correctly if it is not available in the same path as your application.';
384
const FORCEDELETE_WARNING = 'sw-prechache-webpack-plugin [forceDelete]: You are specifying the option forceDelete. This was removed in v0.10. It should not affect your build but should no longer be required.';
385
```
386
387
**Common Error Scenarios:**
388
389
- **Chunk Not Found**: Error thrown when `chunkName` specified in `importScripts` doesn't match any webpack chunk
390
- **Filepath Warning**: Using custom `filepath` may prevent service worker from working if not in the correct scope
391
- **Force Delete Warning**: The `forceDelete` option was removed in v0.10 and should no longer be used
392
- **Conflicting Configuration**: Warning when both `chunkName` and `filename` are specified for import scripts
393
394
Warnings are displayed when `debug: true` is set in the configuration options.
395
396
## Integration Notes
397
398
- **Webpack Compatibility**: Supports webpack 1, 2, 3, and 4
399
- **Hook Usage**: Automatically detects webpack version and uses appropriate hooks (`compiler.hooks` for webpack 4+, `compiler.plugin` for older versions)
400
- **Asset Integration**: Automatically includes all webpack-emitted assets in service worker cache
401
- **Build Timing**: Runs after asset emission to ensure all files are available for caching
402
- **File System**: Uses webpack's output file system for consistent file writing behavior