workbox
sound definitely interesting and might be the way to solve the cache problem when updating the app and automatically
workbox-webpack-plugin
could be chained to webpack and on each build will generate a new list of the resources to cache
but unfortunately can’t be used I did the migration, everything works fine … till I run a --prod
build. workbox-webpack-plugin
will generate a precache-hash.js
file in the www/build
folder containing the list of resource to cache, awesome, but problem is that ionic app-script
try to minify all files under www/build
and unfortunately fails on minifying that particular file
SOLUTION
workbox-build
could be use and chained with gulp (reference: https://developers.google.com/web/tools/workbox/guides/precache-files/workbox-build)
-
remove
sw-toolbox
, installworkbox
andworkbox-build
npm uninstall sw-toolbox --save npm install workbox --save npm install workbox-build --save-dev
-
modify
src/service-worker.js
(example taken from the Ionic pwa toolkit https://github.com/ionic-team/ionic-pwa-toolkit/blob/master/src/sw.js)'use strict'; importScripts('build/workbox-sw.js'); self.workbox.skipWaiting(); self.workbox.clientsClaim(); self.workbox.precaching.precacheAndRoute([]);
-
edit your local copy of
copy.config.js
from Ionic app-script in order to copyworkbox-sw.js
instead ofsw-toolbox.js
to the build dircopySwToolbox: { src: ['{{ROOT}}/node_modules/workbox-sw/build/workbox-sw.js'], dest: '{{BUILD}}' }
-
if you don’t use it yet, install gulp and create a
gulpfile.js
-
edit your gulpfile and add a new task
gulp.task('build-sw', function () { return workboxBuild.injectManifest({ swSrc: 'src/service-worker.js', swDest: 'www/service-worker.js', globDirectory: 'www', globPatterns: [ '**\/*.{js,css,html,png,json,eot,svg,ttf,woff,woff2,svg,ico,jpg}', ] }).then(({count, size, warnings}) => { // Optionally, log any warnings and details. warnings.forEach(console.warn); console.log(`${count} files will be precached, totaling ${size} bytes.`); }); });
-
edit your
package.json
and create a cmd to chain everything"scripts": [ ... "pwa": "ionic-app-scripts build --prod && gulp build-sw" ]
-
modify index.html in order to keep the load of the page performant while loading the service-worker (see https://developers.google.com/web/tools/workbox/guides/get-started) replace the default
serviceWorker
load code in index.html<script> // Check that service workers are registered if ('serviceWorker' in navigator) { // Use the window load event to keep the page load performant window.addEventListener('load', () => { navigator.serviceWorker.register('/service-worker.js') .then(() => console.log('service worker installed')) .catch(err => console.error('Error', err)); }); } </script>
build and enjoy with npm run pwa