PWA updating with precache

This commit is contained in:
Ben Grant 2021-06-16 23:48:43 +10:00
parent 52699840b6
commit 64cd9fc1f5
7 changed files with 75 additions and 177 deletions

View file

@ -1,3 +1,16 @@
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
const path = require('path');
// const fs = require('fs');
// const glob = require('glob');
// const crypto = require('crypto');
// const fileHash = path => {
// let file_buffer = fs.readFileSync(path);
// let sum = crypto.createHash('md5');
// sum.update(file_buffer);
// return sum.digest('hex');
// };
module.exports = function override(config, env) {
config.output.filename = env === 'production'
? 'static/js/[name].[contenthash].js'
@ -7,5 +20,29 @@ module.exports = function override(config, env) {
? 'static/js/[name].[contenthash].chunk.js'
: env === 'development' && 'static/js/[name].chunk.js';
if (env === 'production') {
config.plugins.push(new WorkboxWebpackPlugin.InjectManifest({
swSrc: path.resolve(__dirname, 'src/sw.js'),
exclude: [/\.map$/, /asset-manifest\.json$/, /LICENSE/],
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
additionalManifestEntries: [
// ...glob.sync('./public/i18n/*/*.json').map(file => {
// return ({
// url: file.replace('./public', ''),
// revision: fileHash(file),
// });
// }),
{
url: '/index.css',
revision: null,
},
{
url: '/manifest.json',
revision: null,
},
],
}));
}
return config;
}

View file

@ -40,6 +40,7 @@
"workbox-routing": "^5.1.3",
"workbox-strategies": "^5.1.3",
"workbox-streams": "^5.1.3",
"workbox-window": "^6.1.5",
"zustand": "^3.3.2"
},
"scripts": {
@ -67,6 +68,7 @@
]
},
"devDependencies": {
"react-app-rewired": "^2.1.8"
"react-app-rewired": "^2.1.8",
"workbox-webpack-plugin": "^5.1.3"
}
}

View file

@ -1,8 +1,7 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
import reportWebVitals from './reportWebVitals';
import { Workbox } from 'workbox-window';
import 'i18n';
ReactDOM.render(
@ -12,9 +11,16 @@ ReactDOM.render(
document.getElementById('root')
);
serviceWorkerRegistration.register();
if ('serviceWorker' in navigator) {
const wb = new Workbox('sw.js');
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
wb.addEventListener('installed', event => {
if (event.isUpdate) {
if (window.confirm(`New content is available!. Click OK to refresh`)) {
window.location.reload();
}
}
});
wb.register();
}

View file

@ -28,7 +28,7 @@ const Privacy = () => {
document.title = `${t('privacy:name')} - Crab Fit`;
}, [t]);
useEffect(() => setContent(contentRef.current?.innerText || ''), [contentRef.current]);
useEffect(() => setContent(contentRef.current?.innerText || ''), [contentRef]);
return (
<>

View file

@ -1,137 +0,0 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://cra.link/PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://cra.link/PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://cra.link/PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch((error) => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then((response) => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log('No internet connection found. App is running in offline mode.');
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then((registration) => {
registration.unregister();
})
.catch((error) => {
console.error(error.message);
});
}
}

View file

@ -1,24 +1,15 @@
/* eslint-disable no-restricted-globals */
// This service worker can be customized!
// See https://developers.google.com/web/tools/workbox/modules
// for the list of available Workbox modules, or add any other
// code you'd like.
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.
import { clientsClaim } from 'workbox-core';
import { clientsClaim, skipWaiting } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate, NetworkFirst } from 'workbox-strategies';
skipWaiting();
clientsClaim();
// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
// Injection point
precacheAndRoute(self.__WB_MANIFEST);
// Set up App Shell-style routing, so that all navigation requests
@ -46,8 +37,6 @@ registerRoute(
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);
// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
// Add in any other file extensions or routing criteria as needed.
({ url }) => url.origin === self.location.origin && (
@ -70,21 +59,10 @@ registerRoute(
})
);
// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
// Any other custom service worker logic can go here.
registerRoute(
({ url }) => url.origin === self.location.origin && (
url.pathname.endsWith('.js')
|| url.pathname.endsWith('.css')
|| url.pathname.endsWith('.json')
),
new NetworkFirst({ cacheName: 'res' })
// Add in any other file extensions or routing criteria as needed.
({ url }) => url.origin === self.location.origin && url.pathname.includes('i18n'),
new NetworkFirst({
cacheName: 'i18n',
})
);

View file

@ -11522,6 +11522,11 @@ workbox-core@^5.1.3, workbox-core@^5.1.4:
resolved "https://registry.yarnpkg.com/workbox-core/-/workbox-core-5.1.4.tgz#8bbfb2362ecdff30e25d123c82c79ac65d9264f4"
integrity sha512-+4iRQan/1D8I81nR2L5vcbaaFskZC2CL17TLbvWVzQ4qiF/ytOGF6XeV54pVxAvKUtkLANhk8TyIUMtiMw2oDg==
workbox-core@^6.1.5:
version "6.1.5"
resolved "https://registry.yarnpkg.com/workbox-core/-/workbox-core-6.1.5.tgz#424ff600e2c5448b14ebd58b2f5ac8ed91b73fb9"
integrity sha512-9SOEle7YcJzg3njC0xMSmrPIiFjfsFm9WjwGd5enXmI8Lwk8wLdy63B0nzu5LXoibEmS9k+aWF8EzaKtOWjNSA==
workbox-expiration@^5.1.3, workbox-expiration@^5.1.4:
version "5.1.4"
resolved "https://registry.yarnpkg.com/workbox-expiration/-/workbox-expiration-5.1.4.tgz#92b5df461e8126114943a3b15c55e4ecb920b163"
@ -11588,7 +11593,7 @@ workbox-sw@^5.1.4:
resolved "https://registry.yarnpkg.com/workbox-sw/-/workbox-sw-5.1.4.tgz#2bb34c9f7381f90d84cef644816d45150011d3db"
integrity sha512-9xKnKw95aXwSNc8kk8gki4HU0g0W6KXu+xks7wFuC7h0sembFnTrKtckqZxbSod41TDaGh+gWUA5IRXrL0ECRA==
workbox-webpack-plugin@5.1.4:
workbox-webpack-plugin@5.1.4, workbox-webpack-plugin@^5.1.3:
version "5.1.4"
resolved "https://registry.yarnpkg.com/workbox-webpack-plugin/-/workbox-webpack-plugin-5.1.4.tgz#7bfe8c16e40fe9ed8937080ac7ae9c8bde01e79c"
integrity sha512-PZafF4HpugZndqISi3rZ4ZK4A4DxO8rAqt2FwRptgsDx7NF8TVKP86/huHquUsRjMGQllsNdn4FNl8CD/UvKmQ==
@ -11607,6 +11612,13 @@ workbox-window@^5.1.4:
dependencies:
workbox-core "^5.1.4"
workbox-window@^6.1.5:
version "6.1.5"
resolved "https://registry.yarnpkg.com/workbox-window/-/workbox-window-6.1.5.tgz#017b22342e10c6df6b9672326b575ec950b6cd80"
integrity sha512-akL0X6mAegai2yypnq78RgfazeqvKbsllRtEI4dnbhPcRINEY1NmecFmsQk8SD+zWLK1gw5OdwAOX+zHSRVmeA==
dependencies:
workbox-core "^6.1.5"
worker-farm@^1.7.0:
version "1.7.0"
resolved "https://registry.yarnpkg.com/worker-farm/-/worker-farm-1.7.0.tgz#26a94c5391bbca926152002f69b84a4bf772e5a8"