From a2e02470ecf4a0e9c47dc0f184b54c25ab56e424 Mon Sep 17 00:00:00 2001 From: Joao Maio <10330349+JMaio@users.noreply.github.com> Date: Sat, 26 Dec 2020 23:32:48 +0000 Subject: [PATCH] fix(pwa): explicitly add workbox for PWA support https://github.com/facebook/create-react-app/issues/9776#issuecomment-728945921 --- package.json | 14 +++- src/components/ServiceWorkerWrapper.tsx | 5 +- src/components/render/WebGLCanvas.tsx | 4 +- src/reportWebVitals.ts | 15 ++++ src/service-worker.ts | 80 +++++++++++++++++++ ...Worker.js => serviceWorkerRegistration.ts} | 51 +++++++----- yarn.lock | 36 ++++++--- 7 files changed, 168 insertions(+), 37 deletions(-) create mode 100644 src/reportWebVitals.ts create mode 100644 src/service-worker.ts rename src/{serviceWorker.js => serviceWorkerRegistration.ts} (78%) diff --git a/package.json b/package.json index 7f967e1..2c46a13 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,18 @@ "typeface-roboto": "^1.1.13", "typescript": "^4.1.2", "vec-la-fp": "^1.9.0", + "workbox-background-sync": "^5.1.3", + "workbox-broadcast-update": "^5.1.3", + "workbox-cacheable-response": "^5.1.3", + "workbox-core": "^5.1.3", + "workbox-expiration": "^5.1.3", + "workbox-google-analytics": "^5.1.3", + "workbox-navigation-preload": "^5.1.3", + "workbox-precaching": "^5.1.3", + "workbox-range-requests": "^5.1.3", + "workbox-routing": "^5.1.3", + "workbox-strategies": "^5.1.3", + "workbox-streams": "^5.1.3", "wouter": "^2.6.0" }, "devDependencies": { @@ -86,4 +98,4 @@ "lint-staged": { "./src/**/*.{js,jsx,ts,tsx}": "pretty-quick" } -} \ No newline at end of file +} diff --git a/src/components/ServiceWorkerWrapper.tsx b/src/components/ServiceWorkerWrapper.tsx index 9af5307..42294bd 100644 --- a/src/components/ServiceWorkerWrapper.tsx +++ b/src/components/ServiceWorkerWrapper.tsx @@ -3,7 +3,10 @@ import { Button, Snackbar } from '@material-ui/core'; import Alert from '@material-ui/lab/Alert'; import React, { FC, useEffect } from 'react'; -import * as serviceWorker from '../serviceWorker'; +import * as serviceWorker from '../serviceWorkerRegistration'; +// service worker config has been removed from CRA / react-scripts 4.0 +// https://github.com/facebook/create-react-app/issues/9776#issuecomment-728945921 +// files sourced from https://github.com/cra-template/pwa/tree/master/packages/cra-template-pwa-typescript const ServiceWorkerWrapper: FC = () => { const [showReload, setShowReload] = React.useState(false); diff --git a/src/components/render/WebGLCanvas.tsx b/src/components/render/WebGLCanvas.tsx index d6d6611..31c151f 100644 --- a/src/components/render/WebGLCanvas.tsx +++ b/src/components/render/WebGLCanvas.tsx @@ -50,7 +50,7 @@ const WebGLCanvas = React.forwardRef( // https://www.khronos.org/webgl/wiki/HandlingContextLost canvasRef.current.addEventListener( 'webglcontextlost', - (event) => { + (event: Event) => { console.error('WebGL context lost!'); event.preventDefault(); // trigger an error alert in future? @@ -59,7 +59,7 @@ const WebGLCanvas = React.forwardRef( ); canvasRef.current.addEventListener( 'webglcontextrestored', - (event) => { + (event: Event) => { console.error('WebGL context restored! Setting up...'); setupCanvas(); }, diff --git a/src/reportWebVitals.ts b/src/reportWebVitals.ts new file mode 100644 index 0000000..49a2a16 --- /dev/null +++ b/src/reportWebVitals.ts @@ -0,0 +1,15 @@ +import { ReportHandler } from 'web-vitals'; + +const reportWebVitals = (onPerfEntry?: ReportHandler) => { + if (onPerfEntry && onPerfEntry instanceof Function) { + import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { + getCLS(onPerfEntry); + getFID(onPerfEntry); + getFCP(onPerfEntry); + getLCP(onPerfEntry); + getTTFB(onPerfEntry); + }); + } +}; + +export default reportWebVitals; diff --git a/src/service-worker.ts b/src/service-worker.ts new file mode 100644 index 0000000..8b78e70 --- /dev/null +++ b/src/service-worker.ts @@ -0,0 +1,80 @@ +/// +/* 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 { ExpirationPlugin } from 'workbox-expiration'; +import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching'; +import { registerRoute } from 'workbox-routing'; +import { StaleWhileRevalidate } from 'workbox-strategies'; + +declare const self: ServiceWorkerGlobalScope; + +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 +precacheAndRoute(self.__WB_MANIFEST); + +// Set up App Shell-style routing, so that all navigation requests +// are fulfilled with your index.html shell. Learn more at +// https://developers.google.com/web/fundamentals/architecture/app-shell +const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$'); +registerRoute( + // Return false to exempt requests from being fulfilled by index.html. + ({ request, url }: { request: Request; url: URL }) => { + // If this isn't a navigation, skip. + if (request.mode !== 'navigate') { + return false; + } + + // If this is a URL that starts with /_, skip. + if (url.pathname.startsWith('/_')) { + return false; + } + + // If this looks like a URL for a resource, because it contains + // a file extension, skip. + if (url.pathname.match(fileExtensionRegexp)) { + return false; + } + + // Return true to signal that we want to use the handler. + return true; + }, + 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 && url.pathname.endsWith('.png'), + // Customize this strategy as needed, e.g., by changing to CacheFirst. + new StaleWhileRevalidate({ + cacheName: 'images', + plugins: [ + // Ensure that once this runtime cache reaches a maximum size the + // least-recently used images are removed. + new ExpirationPlugin({ maxEntries: 50 }), + ], + }), +); + +// 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. diff --git a/src/serviceWorker.js b/src/serviceWorkerRegistration.ts similarity index 78% rename from src/serviceWorker.js rename to src/serviceWorkerRegistration.ts index f8c7e50..f6eb5d6 100644 --- a/src/serviceWorker.js +++ b/src/serviceWorkerRegistration.ts @@ -8,19 +8,24 @@ // resources are updated in the background. // To learn more about the benefits of this model and instructions on how to -// opt-in, read https://bit.ly/CRA-PWA +// 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.1/8 is considered localhost for IPv4. + // 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}$/ - ) + /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/, + ), ); -export function register(config) { +type Config = { + onSuccess?: (registration: ServiceWorkerRegistration) => void; + onUpdate?: (registration: ServiceWorkerRegistration) => void; +}; + +export function register(config?: Config): void { 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); @@ -43,7 +48,7 @@ export function register(config) { navigator.serviceWorker.ready.then(() => { console.log( 'This web app is being served cache-first by a service ' + - 'worker. To learn more, visit https://bit.ly/CRA-PWA' + 'worker. To learn more, visit https://cra.link/PWA', ); }); } else { @@ -54,10 +59,10 @@ export function register(config) { } } -function registerValidSW(swUrl, config) { +function registerValidSW(swUrl: string, config?: Config) { navigator.serviceWorker .register(swUrl) - .then(registration => { + .then((registration) => { registration.onupdatefound = () => { const installingWorker = registration.installing; if (installingWorker == null) { @@ -71,7 +76,7 @@ function registerValidSW(swUrl, config) { // 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://bit.ly/CRA-PWA.' + 'tabs for this page are closed. See https://cra.link/PWA.', ); // Execute callback @@ -93,15 +98,17 @@ function registerValidSW(swUrl, config) { }; }; }) - .catch(error => { + .catch((error) => { console.error('Error during service worker registration:', error); }); } -function checkValidServiceWorker(swUrl, config) { +function checkValidServiceWorker(swUrl: string, config?: Config) { // Check if the service worker can be found. If it can't reload the page. - fetch(swUrl) - .then(response => { + 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 ( @@ -109,7 +116,7 @@ function checkValidServiceWorker(swUrl, config) { (contentType != null && contentType.indexOf('javascript') === -1) ) { // No service worker found. Probably a different app. Reload the page. - navigator.serviceWorker.ready.then(registration => { + navigator.serviceWorker.ready.then((registration) => { registration.unregister().then(() => { window.location.reload(); }); @@ -120,16 +127,18 @@ function checkValidServiceWorker(swUrl, config) { } }) .catch(() => { - console.log( - 'No internet connection found. App is running in offline mode.' - ); + console.log('No internet connection found. App is running in offline mode.'); }); } -export function unregister() { +export function unregister(): void { if ('serviceWorker' in navigator) { - navigator.serviceWorker.ready.then(registration => { - registration.unregister(); - }); + navigator.serviceWorker.ready + .then((registration) => { + registration.unregister(); + }) + .catch((error) => { + console.error(error.message); + }); } } diff --git a/yarn.lock b/yarn.lock index ee95741..4767fbd 100644 --- a/yarn.lock +++ b/yarn.lock @@ -11363,6 +11363,18 @@ fsevents@~2.1.2: typescript: ^4.1.2 vec-la-fp: ^1.9.0 web-vitals: ^1.0.1 + workbox-background-sync: ^5.1.3 + workbox-broadcast-update: ^5.1.3 + workbox-cacheable-response: ^5.1.3 + workbox-core: ^5.1.3 + workbox-expiration: ^5.1.3 + workbox-google-analytics: ^5.1.3 + workbox-navigation-preload: ^5.1.3 + workbox-precaching: ^5.1.3 + workbox-range-requests: ^5.1.3 + workbox-routing: ^5.1.3 + workbox-strategies: ^5.1.3 + workbox-streams: ^5.1.3 wouter: ^2.6.0 languageName: unknown linkType: soft @@ -17764,7 +17776,7 @@ typescript@^4.1.2: languageName: node linkType: hard -"workbox-background-sync@npm:^5.1.4": +"workbox-background-sync@npm:^5.1.3, workbox-background-sync@npm:^5.1.4": version: 5.1.4 resolution: "workbox-background-sync@npm:5.1.4" dependencies: @@ -17773,7 +17785,7 @@ typescript@^4.1.2: languageName: node linkType: hard -"workbox-broadcast-update@npm:^5.1.4": +"workbox-broadcast-update@npm:^5.1.3, workbox-broadcast-update@npm:^5.1.4": version: 5.1.4 resolution: "workbox-broadcast-update@npm:5.1.4" dependencies: @@ -17826,7 +17838,7 @@ typescript@^4.1.2: languageName: node linkType: hard -"workbox-cacheable-response@npm:^5.1.4": +"workbox-cacheable-response@npm:^5.1.3, workbox-cacheable-response@npm:^5.1.4": version: 5.1.4 resolution: "workbox-cacheable-response@npm:5.1.4" dependencies: @@ -17835,14 +17847,14 @@ typescript@^4.1.2: languageName: node linkType: hard -"workbox-core@npm:^5.1.4": +"workbox-core@npm:^5.1.3, workbox-core@npm:^5.1.4": version: 5.1.4 resolution: "workbox-core@npm:5.1.4" checksum: eaa6021ef9d7f3046619d09904171121286dee8c20299b00f4a06d85e8a549c0345f70cf5a5cb47c270641ffd3e319b40479c7a7bd4025c651f9ee215ee27014 languageName: node linkType: hard -"workbox-expiration@npm:^5.1.4": +"workbox-expiration@npm:^5.1.3, workbox-expiration@npm:^5.1.4": version: 5.1.4 resolution: "workbox-expiration@npm:5.1.4" dependencies: @@ -17851,7 +17863,7 @@ typescript@^4.1.2: languageName: node linkType: hard -"workbox-google-analytics@npm:^5.1.4": +"workbox-google-analytics@npm:^5.1.3, workbox-google-analytics@npm:^5.1.4": version: 5.1.4 resolution: "workbox-google-analytics@npm:5.1.4" dependencies: @@ -17863,7 +17875,7 @@ typescript@^4.1.2: languageName: node linkType: hard -"workbox-navigation-preload@npm:^5.1.4": +"workbox-navigation-preload@npm:^5.1.3, workbox-navigation-preload@npm:^5.1.4": version: 5.1.4 resolution: "workbox-navigation-preload@npm:5.1.4" dependencies: @@ -17872,7 +17884,7 @@ typescript@^4.1.2: languageName: node linkType: hard -"workbox-precaching@npm:^5.1.4": +"workbox-precaching@npm:^5.1.3, workbox-precaching@npm:^5.1.4": version: 5.1.4 resolution: "workbox-precaching@npm:5.1.4" dependencies: @@ -17881,7 +17893,7 @@ typescript@^4.1.2: languageName: node linkType: hard -"workbox-range-requests@npm:^5.1.4": +"workbox-range-requests@npm:^5.1.3, workbox-range-requests@npm:^5.1.4": version: 5.1.4 resolution: "workbox-range-requests@npm:5.1.4" dependencies: @@ -17890,7 +17902,7 @@ typescript@^4.1.2: languageName: node linkType: hard -"workbox-routing@npm:^5.1.4": +"workbox-routing@npm:^5.1.3, workbox-routing@npm:^5.1.4": version: 5.1.4 resolution: "workbox-routing@npm:5.1.4" dependencies: @@ -17899,7 +17911,7 @@ typescript@^4.1.2: languageName: node linkType: hard -"workbox-strategies@npm:^5.1.4": +"workbox-strategies@npm:^5.1.3, workbox-strategies@npm:^5.1.4": version: 5.1.4 resolution: "workbox-strategies@npm:5.1.4" dependencies: @@ -17909,7 +17921,7 @@ typescript@^4.1.2: languageName: node linkType: hard -"workbox-streams@npm:^5.1.4": +"workbox-streams@npm:^5.1.3, workbox-streams@npm:^5.1.4": version: 5.1.4 resolution: "workbox-streams@npm:5.1.4" dependencies: