I am trying to generate a service worker with sw-precache, which should cache external resources. With the caching of resources that lie next to no problems, this is done in this way:

gulp.task('generate-service-worker', ['copy-sw-scripts'], () => { const rootDir = 'dist'; const filepath = path.join(rootDir, 'service-worker.js'); return swPrecache.write(filepath, { cacheId: pkg.name || 'app', staticFileGlobs: [ `${rootDir}/images/**/*`, `${rootDir}/fonts/**/*.woff2`, `${rootDir}/scripts/**/*.js`, `${rootDir}/styles/**/*.css`, `${rootDir}/*.{html,json}` ], stripPrefix: rootDir + '/' }); }); 

I try to generate a service worker that will cache external resources like this:

 gulp.task('generate-service-worker', ['copy-sw-scripts'], () => { const rootDir = 'dist'; const filepath = path.join(rootDir, 'service-worker.js'); return swPrecache.write(filepath, { cacheId: pkg.name || 'app', importScripts: [ 'scripts/sw/sw-toolbox.js', 'scripts/sw/runtime-caching.js' ], runtimeCaching: [ { urlPattern: /^https:\/\/cdn\.mysite\.ua\/assets/, handler: 'networkFirst' } ], stripPrefix: rootDir + '/' }); }); 

But it does not bring the desired result. How to do it right?

I use sw-precache, sw-toolbox.

    1 answer 1

    Everything turned out to be quite simple, along with dynamic caching of files from CDN, it was also necessary to cache “local” files, so everything works:

     gulp.task('generate-service-worker', ['copy-sw-scripts'], () => { const rootDir = 'dist'; const filepath = path.join(rootDir, 'service-worker.js'); return swPrecache.write(filepath, { cacheId: pkg.name || 'app', importScripts: [ 'scripts/sw/sw-toolbox.js', 'scripts/sw/runtime-caching.js' ], staticFileGlobs: [ `${rootDir}/*.{html,json}` ], runtimeCaching: [ { urlPattern: /^https:\/\/cdn\.mysite\.ua\/assets/, handler: 'networkFirst' } ], stripPrefix: rootDir + '/' }); });