1
yarn add --dev sw-precache-webpack-plugin
1
2
3
4
5
6
7
8
9
10
11
12
13
// webpack
new SWPrecachePlugin({
cacheId: 'demo',
filename: 'service-worker.js',
dontCacheBustUrlsMatching: false,
staticFileGlobsIgnorePatterns: [
/index\.html$/,
/\.map$/,
/\.css$/,
/\.svg$/,
/\.eot$/,
]
})

This will generate service-worker.js in dist.

Add Router

1
app.use('/service-worker.js', serve('./dist/service-worker.js'))

Note: [name].[ext]?[hash] will not be found by sw-precache(hash will be ignored), so filename should be specified like [name].[hash].[ext] or so.

Cache files who are not bundled by webpack.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
new SWPrecachePlugin({
cacheId: 'demo',
filename: 'service-worker.js',
minify: true,
// add two lines
mergeStaticConfig: true,
staticFileBlogs: [
path.join(__dirname, '../dist/static/*.*'),
],
dontCacheBustUrlsMatching: false,
staticFileGlobsIgnorePatterns: [
/\.index\.html$/,
/\.map$/,
/\.css$/,
/\.svg$/,
/\.eot$/,
]
})

About the Request URL

The images are cached in /dist/static/*, while the request url is /static/*.

In dev it can be proxied by webpack.

In prod it can be delegated by nginx.

But the plugin can fix it by itself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
new SWPrecachePlugin({
cacheId: 'demo',
filename: 'service-worker.js',
minify: true,
mergeStaticConfig: true,
staticFileGlobs: [
path.join(__dirname, '../dist/static/*.*')
],
stripPrefixMulti: {
[path.join(__dirname, '../dist/static')]: '/static'
},
dontCacheBustUrlsMatching: false,
staticFileGlobsIgnorePatterns: [
/\.index\.html$/,
/\.map$/,
/\.css$/,
/\.svg$/,
/\.eot$/,
]
})

Note: dontCacheBustUrlsMatching: false will set cached key as http://domain/path/to/filename?hash, whose hash will change if the bundled file changed.