Skip to content

Commit a57e9db

Browse files
BilkisBilkis
Bilkis
authored and
Bilkis
committed
add pwa
1 parent ec1d436 commit a57e9db

File tree

6 files changed

+357
-198
lines changed

6 files changed

+357
-198
lines changed

package.json

+17-6
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,6 @@
77
"@emotion/styled": "^11.3.0",
88
"@mui/material": "^5.0.3",
99
"@mui/styles": "^5.0.1",
10-
"@testing-library/jest-dom": "^5.14.1",
11-
"@testing-library/react": "^12.1.2",
12-
"@testing-library/user-event": "^13.3.0",
1310
"axios": "^0.24.0",
1411
"axios-rate-limit": "^1.3.0",
1512
"react": "^17.0.2",
@@ -22,13 +19,26 @@
2219
"redux-persist": "^6.0.0",
2320
"redux-thunk": "^2.3.0",
2421
"sweetalert2": "^11.1.9",
25-
"web-vitals": "^2.1.1"
22+
"web-vitals": "^2.1.1",
23+
"workbox-background-sync": "^5.1.4",
24+
"workbox-broadcast-update": "^5.1.4",
25+
"workbox-cacheable-response": "^5.1.4",
26+
"workbox-core": "^5.1.4",
27+
"workbox-expiration": "^5.1.4",
28+
"workbox-google-analytics": "^5.1.4",
29+
"workbox-navigation-preload": "^5.1.4",
30+
"workbox-precaching": "^5.1.4",
31+
"workbox-range-requests": "^5.1.4",
32+
"workbox-routing": "^5.1.4",
33+
"workbox-strategies": "^5.1.4",
34+
"workbox-streams": "^5.1.4"
2635
},
2736
"scripts": {
2837
"start": "react-scripts start",
2938
"build": "react-scripts build",
3039
"test": "react-scripts test",
31-
"eject": "react-scripts eject"
40+
"eject": "react-scripts eject",
41+
"analyze": "yarn run build && source-map-explorer 'build/static/js/*.js'"
3242
},
3343
"eslintConfig": {
3444
"extends": [
@@ -49,6 +59,7 @@
4959
]
5060
},
5161
"devDependencies": {
52-
"redux-logger": "^3.0.6"
62+
"redux-logger": "^3.0.6",
63+
"source-map-explorer": "^2.5.2"
5364
}
5465
}

src/index.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1+
import "style/main.style.css";
12
import React from "react";
2-
import ReactDOM from "react-dom";
33
import Root from "app/root";
4+
import ReactDOM from "react-dom";
45
import reportWebVitals from "./reportWebVitals";
56
import { BrowserRouter } from "react-router-dom";
6-
import "style/main.style.css";
7+
import * as serviceWorkerRegistration from "./serviceWorkerRegistration";
78

89
ReactDOM.render(
910
<BrowserRouter>
@@ -12,6 +13,11 @@ ReactDOM.render(
1213
document.getElementById("root")
1314
);
1415

16+
// If you want your app to work offline and load faster, you can change
17+
// unregister() to register() below. Note this comes with some pitfalls.
18+
// Learn more about service workers: https://cra.link/PWA
19+
serviceWorkerRegistration.register();
20+
1521
// If you want to start measuring performance in your app, pass a function
1622
// to log results (for example: reportWebVitals(console.log))
1723
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals

src/redux/middleware.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import logger from "redux-logger";
1+
// import logger from "redux-logger";
22
import thunk from "redux-thunk";
33

44
// dev middleware
5-
const DEV_MIDDLEWARE = [logger];
5+
const DEV_MIDDLEWARE = [];
66

77
// main middleware
88
let MAIN_MIDDLEWARE = [thunk];

src/service-worker.js

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/* eslint-disable no-restricted-globals */
2+
3+
// This service worker can be customized!
4+
// See https://developers.google.com/web/tools/workbox/modules
5+
// for the list of available Workbox modules, or add any other
6+
// code you'd like.
7+
// You can also remove this file if you'd prefer not to use a
8+
// service worker, and the Workbox build step will be skipped.
9+
10+
import { clientsClaim } from 'workbox-core';
11+
import { ExpirationPlugin } from 'workbox-expiration';
12+
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
13+
import { registerRoute } from 'workbox-routing';
14+
import { StaleWhileRevalidate } from 'workbox-strategies';
15+
16+
clientsClaim();
17+
18+
// Precache all of the assets generated by your build process.
19+
// Their URLs are injected into the manifest variable below.
20+
// This variable must be present somewhere in your service worker file,
21+
// even if you decide not to use precaching. See https://cra.link/PWA
22+
precacheAndRoute(self.__WB_MANIFEST);
23+
24+
// Set up App Shell-style routing, so that all navigation requests
25+
// are fulfilled with your index.html shell. Learn more at
26+
// https://developers.google.com/web/fundamentals/architecture/app-shell
27+
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
28+
registerRoute(
29+
// Return false to exempt requests from being fulfilled by index.html.
30+
({ request, url }) => {
31+
// If this isn't a navigation, skip.
32+
if (request.mode !== 'navigate') {
33+
return false;
34+
} // If this is a URL that starts with /_, skip.
35+
36+
if (url.pathname.startsWith('/_')) {
37+
return false;
38+
} // If this looks like a URL for a resource, because it contains // a file extension, skip.
39+
40+
if (url.pathname.match(fileExtensionRegexp)) {
41+
return false;
42+
} // Return true to signal that we want to use the handler.
43+
44+
return true;
45+
},
46+
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
47+
);
48+
49+
// An example runtime caching route for requests that aren't handled by the
50+
// precache, in this case same-origin .png requests like those from in public/
51+
registerRoute(
52+
// Add in any other file extensions or routing criteria as needed.
53+
({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'), // Customize this strategy as needed, e.g., by changing to CacheFirst.
54+
new StaleWhileRevalidate({
55+
cacheName: 'images',
56+
plugins: [
57+
// Ensure that once this runtime cache reaches a maximum size the
58+
// least-recently used images are removed.
59+
new ExpirationPlugin({ maxEntries: 50 }),
60+
],
61+
})
62+
);
63+
64+
// This allows the web app to trigger skipWaiting via
65+
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
66+
self.addEventListener('message', (event) => {
67+
if (event.data && event.data.type === 'SKIP_WAITING') {
68+
self.skipWaiting();
69+
}
70+
});
71+
72+
// Any other custom service worker logic can go here.

src/serviceWorkerRegistration.js

+137
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
// This optional code is used to register a service worker.
2+
// register() is not called by default.
3+
4+
// This lets the app load faster on subsequent visits in production, and gives
5+
// it offline capabilities. However, it also means that developers (and users)
6+
// will only see deployed updates on subsequent visits to a page, after all the
7+
// existing tabs open on the page have been closed, since previously cached
8+
// resources are updated in the background.
9+
10+
// To learn more about the benefits of this model and instructions on how to
11+
// opt-in, read https://cra.link/PWA
12+
13+
const isLocalhost = Boolean(
14+
window.location.hostname === 'localhost' ||
15+
// [::1] is the IPv6 localhost address.
16+
window.location.hostname === '[::1]' ||
17+
// 127.0.0.0/8 are considered localhost for IPv4.
18+
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
19+
);
20+
21+
export function register(config) {
22+
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
23+
// The URL constructor is available in all browsers that support SW.
24+
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
25+
if (publicUrl.origin !== window.location.origin) {
26+
// Our service worker won't work if PUBLIC_URL is on a different origin
27+
// from what our page is served on. This might happen if a CDN is used to
28+
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
29+
return;
30+
}
31+
32+
window.addEventListener('load', () => {
33+
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
34+
35+
if (isLocalhost) {
36+
// This is running on localhost. Let's check if a service worker still exists or not.
37+
checkValidServiceWorker(swUrl, config);
38+
39+
// Add some additional logging to localhost, pointing developers to the
40+
// service worker/PWA documentation.
41+
navigator.serviceWorker.ready.then(() => {
42+
console.log(
43+
'This web app is being served cache-first by a service ' +
44+
'worker. To learn more, visit https://cra.link/PWA'
45+
);
46+
});
47+
} else {
48+
// Is not localhost. Just register service worker
49+
registerValidSW(swUrl, config);
50+
}
51+
});
52+
}
53+
}
54+
55+
function registerValidSW(swUrl, config) {
56+
navigator.serviceWorker
57+
.register(swUrl)
58+
.then((registration) => {
59+
registration.onupdatefound = () => {
60+
const installingWorker = registration.installing;
61+
if (installingWorker == null) {
62+
return;
63+
}
64+
installingWorker.onstatechange = () => {
65+
if (installingWorker.state === 'installed') {
66+
if (navigator.serviceWorker.controller) {
67+
// At this point, the updated precached content has been fetched,
68+
// but the previous service worker will still serve the older
69+
// content until all client tabs are closed.
70+
console.log(
71+
'New content is available and will be used when all ' +
72+
'tabs for this page are closed. See https://cra.link/PWA.'
73+
);
74+
75+
// Execute callback
76+
if (config && config.onUpdate) {
77+
config.onUpdate(registration);
78+
}
79+
} else {
80+
// At this point, everything has been precached.
81+
// It's the perfect time to display a
82+
// "Content is cached for offline use." message.
83+
console.log('Content is cached for offline use.');
84+
85+
// Execute callback
86+
if (config && config.onSuccess) {
87+
config.onSuccess(registration);
88+
}
89+
}
90+
}
91+
};
92+
};
93+
})
94+
.catch((error) => {
95+
console.error('Error during service worker registration:', error);
96+
});
97+
}
98+
99+
function checkValidServiceWorker(swUrl, config) {
100+
// Check if the service worker can be found. If it can't reload the page.
101+
fetch(swUrl, {
102+
headers: { 'Service-Worker': 'script' },
103+
})
104+
.then((response) => {
105+
// Ensure service worker exists, and that we really are getting a JS file.
106+
const contentType = response.headers.get('content-type');
107+
if (
108+
response.status === 404 ||
109+
(contentType != null && contentType.indexOf('javascript') === -1)
110+
) {
111+
// No service worker found. Probably a different app. Reload the page.
112+
navigator.serviceWorker.ready.then((registration) => {
113+
registration.unregister().then(() => {
114+
window.location.reload();
115+
});
116+
});
117+
} else {
118+
// Service worker found. Proceed as normal.
119+
registerValidSW(swUrl, config);
120+
}
121+
})
122+
.catch(() => {
123+
console.log('No internet connection found. App is running in offline mode.');
124+
});
125+
}
126+
127+
export function unregister() {
128+
if ('serviceWorker' in navigator) {
129+
navigator.serviceWorker.ready
130+
.then((registration) => {
131+
registration.unregister();
132+
})
133+
.catch((error) => {
134+
console.error(error.message);
135+
});
136+
}
137+
}

0 commit comments

Comments
 (0)