تحويل موقع React الى PWA

Image drop

ميزات ستحققها من خلال تحويل موقعك الي PWA:

  • السرعة

  • العمل Offline

  • Server Side Update

  • امكانية الاستفادة من عتاد الأجهزة والاشعارات

  • تطبيق هايبرد: Android, iOS, Windows, Linux, macOS


الخطوات

ضمن ملف الـ index.js أضف الكود التالي:

import * as serviceWorkerRegistration from './serviceWorkerRegistration'; . . . // End of file serviceWorkerRegistration.register();

ضمن مجلد الـ src أنشأ ملف باسم “service-worker.js“ والصق الكود التالي:

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"; clientsClaim(); /* eslint-disable-next-line no-restricted-globals */ precacheAndRoute(self.__WB_MANIFEST); const fileExtensionRegexp = new RegExp("/[^/?]+\\.[^/]+$"); registerRoute(({ request, url }) => { if (request.mode !== "navigate") { return false; } if (url.pathname.startsWith("/_")) { return false; } if (url.pathname.match(fileExtensionRegexp)) { return false; } return true; }, createHandlerBoundToURL(process.env.PUBLIC_URL + "/index.html")); registerRoute( ({ url }) => /* eslint-disable-next-line no-restricted-globals */ url.origin === self.location.origin && url.pathname.endsWith(".png"), new StaleWhileRevalidate({ cacheName: "images", plugins: [new ExpirationPlugin({ maxEntries: 50 })], }) ); /* eslint-disable-next-line no-restricted-globals */ self.addEventListener("message", (event) => { if (event.data && event.data.type === "SKIP_WAITING") { /* eslint-disable-next-line no-restricted-globals */ self.skipWaiting(); } });

ضمن مجلد الـ src أيضا أشأ ملف أخر باسم “serviceWorkerRegistration.js“ والصق الكود التالي:

const isLocalhost = Boolean( window.location.hostname === 'localhost' || window.location.hostname === '[::1]' || 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) { const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); if (publicUrl.origin !== window.location.origin) { return; } window.addEventListener('load', () => { const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; if (isLocalhost) { checkValidServiceWorker(swUrl, config); 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 { 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) { console.log( 'New content is available and will be used when all ' + 'tabs for this page are closed. See https://cra.link/PWA.' ); if (config && config.onUpdate) { config.onUpdate(registration); } } else { console.log('Content is cached for offline use.'); if (config && config.onSuccess) { config.onSuccess(registration); } } } }; }; }) .catch((error) => { console.error('Error during service worker registration:', error); }); } function checkValidServiceWorker(swUrl, config) { fetch(swUrl, { headers: { 'Service-Worker': 'script' }, }) .then((response) => { const contentType = response.headers.get('content-type'); if ( response.status === 404 || (contentType != null && contentType.indexOf('javascript') === -1) ) { navigator.serviceWorker.ready.then((registration) => { registration.unregister().then(() => { window.location.reload(); }); }); } else { 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); }); } }

قم باضافة الكود التالي الى ملف manifest.json الموجود ضمن مجلد الـ public.

{ "src": "maskable_icon_x512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }

مثال عن الكود: هنا

استخدم هذا الموقع لتوليد صور متعددة الاحجام من خلال صورة واحدة وأضفها الى مجلد الـ public.


Join