Skip to content

Commit

Permalink
fix(pwa): explicitly add workbox for PWA support
Browse files Browse the repository at this point in the history
  • Loading branch information
JMaio committed Dec 26, 2020
1 parent 99f71a2 commit a2e0247
Show file tree
Hide file tree
Showing 7 changed files with 168 additions and 37 deletions.
14 changes: 13 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down Expand Up @@ -86,4 +98,4 @@
"lint-staged": {
"./src/**/*.{js,jsx,ts,tsx}": "pretty-quick"
}
}
}
5 changes: 4 additions & 1 deletion src/components/ServiceWorkerWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions src/components/render/WebGLCanvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const WebGLCanvas = React.forwardRef<HTMLCanvasElement, WebGLCanvasProps>(
// 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?
Expand All @@ -59,7 +59,7 @@ const WebGLCanvas = React.forwardRef<HTMLCanvasElement, WebGLCanvasProps>(
);
canvasRef.current.addEventListener(
'webglcontextrestored',
(event) => {
(event: Event) => {
console.error('WebGL context restored! Setting up...');
setupCanvas();
},
Expand Down
15 changes: 15 additions & 0 deletions src/reportWebVitals.ts
Original file line number Diff line number Diff line change
@@ -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;
80 changes: 80 additions & 0 deletions src/service-worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/// <reference lib="webworker" />
/* 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.
51 changes: 30 additions & 21 deletions src/serviceWorker.js → src/serviceWorkerRegistration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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 {
Expand All @@ -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) {
Expand All @@ -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
Expand All @@ -93,23 +98,25 @@ 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 (
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 => {
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
Expand All @@ -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);
});
}
}
36 changes: 24 additions & 12 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand Down

0 comments on commit a2e0247

Please sign in to comment.