Mobil ilovalar foydalanuvchilarga kerakli xizmatlarni tez va qulay tarzda taqdim etish qobiliyati tufayli korxonalar uchun deyarli ajralmas narsaga aylandi. Ammo, agar men sizga Internetda mobil ilovaga o'xshash tajribaga ega bo'lish mumkinligini aytsam nima bo'ladi? Progressive Web Apps (PWA) aynan shu maqsadda.
Top Design Firms so‘rovi shuni ko‘rsatadiki, mobil ilovalarga talab ortib bormoqda. 2022-yilda kichik biznesning deyarli yarmi – 48 foizi mobil ilovalariga ega bo‘lgan bo‘lsa, 2021-yilda bu ko‘rsatkich 32 foizni tashkil etgan bo‘lsa, bu ko‘rsatkich barcha platformalarda mobil aloqaga o‘xshash o‘zaro aloqalarni talab qiluvchi foydalanuvchi ehtiyojlarining o‘zgarishini ko‘rsatadi.
PWA-ni ishlab chiqish orqali korxonalar ushbu mahalliy ilova tajribasini veb-brauzer orqali to'g'ridan-to'g'ri taqdim etishi mumkin, bu esa oxirgi foydalanuvchilarga alohida mobil ilovaga ehtiyoj sezmasdan ishonchli va qiziqarli dasturni taqdim etishi mumkin.
Progressiv veb-ilova - bu foydalanuvchilarga mobil qurilmalarga o'xshash mahalliy qo'llab-quvvatlashni ta'minlaydigan ilova bo'lib, ular Androiddan iOS va ish stollarigacha o'zgarib turadigan platformaga xos mulohazalar bilan tuziladi. Ular engil, barcha qurilmalarda foydalanish mumkin va internetga ulanganda avtomatik yangilanadi.
Yaqinda men NextJs ilovamni Progressive Web ilovasiga aylantirish uchun eng yaxshi yoʻl izlanayotgan edim, Reddit’ning keyingi Next.js yangilanishlari, jumladan PWA’larni mahalliy qoʻllab-quvvatlash haqida quyida keltirilgan izohiga duch keldim.
Bu erda sharhni tekshiring.
Yangilanishni ko'rib chiqqandan so'ng, aytishim mumkinki, PWA yaratish hech qachon oson bo'lmagan va men buni isbotlayman.
PS: Ilovangizni PWA sifatida tan olish uchun ikkita fayl juda muhim - manifest fayli va xizmat ishchi fayli .
npx create-next-app@latest my-pwa-app
Yoki
yarn create next-app my-pwa-app
Buyruqni ishga tushirgandan so'ng, o'rnatish xususiyatlari uchun ko'rsatmalarga rioya qiling, so'ngra loyiha katalogiga o'ting
cd my-pwa-app
Dev serverini ishga tushiring
npm run dev
app
katalogida manifest.json
yoki manifest.ts
faylini yarating.
import type { MetadataRoute } from 'next' export default function manifest(): MetadataRoute.Manifest { return { name: 'Next.js PWA', short_name: 'NextPWA', description: 'A Progressive Web App built with Next.js', start_url: '/', display: 'standalone', background_color: '#ffffff', theme_color: '#000000', icons: [ { src: '/icon-192x192.png', sizes: '192x192', type: 'image/png', }, { src: '/icon-512x512.png', sizes: '512x512', type: 'image/png', }, ], } }
standalone
minimal-ui
fullscreen
yoki browser
bo'lishi mumkinsrc
, size
va type
ko'rsatib, turli platformalarda ishlatiladigan piktogrammalarning xususiyatlarini o'z ichiga oladi. PWA uchun kamida 192x192
va 512x512
o'lchamdagi piktogrammalarga ega bo'lish muhimdir.Manifest-generator kabi veb-saytlar manifest faylini va turli o'lchamdagi piktogrammalarni tezda yaratish uchun ishlatilishi mumkin
Xizmat xodimi push hodisalarini tinglaydi va push bildirishnomalari uchun quyidagi funksiyani bajaradi
self.addEventListener("push", function (event) { if (event.data) { const data = event.data.json(); const options = { body: data.body, icon: data.icon || '/icon.png', badge: "/icons/timer-icon-144.png", vibrate: [100, 50, 100], data: { dateOfArrival: Date.now(), primaryKey: "5", }, }; event.waitUntil(self.registration.showNotification(data.title, options)); } }); self.addEventListener("notificationclick", function (event) { console.log("Notification click received."); event.notification.close(); event.waitUntil(clients.openWindow("<https://your-website.com>")); //This should be the url to your website });
Xizmat ko'rsatuvchi xodimni ro'yxatdan o'tkazish uchun siz xizmat ko'rsatuvchi xodim yaratilgan marshrutni ko'rsatishingiz kerak.
const registration = await navigator.serviceWorker.register("/sw.js", { //provide the route to the service worker scope: "/", updateViaCache: "none", });
Bildirishnomalar va obunalarni boshqarish uchun web-push-ni o'rnating
npm install web-push --save
Keyin obunani olishimiz kerak, agar foydalanuvchida obuna bo'lsa yoki foydalanuvchini voqealarni surish uchun obuna bo'lsa. Haqiqiy dasturda ushbu obuna saqlash uchun serverga yuborilishi kerak
async function registerServiceWorker() { const registration = await navigator.serviceWorker.register("/sw.js", { scope: "/", updateViaCache: "none", }); const sub = await registration.pushManager.getSubscription(); if (sub) { setSubscription(sub); //This would be sent to a server } else { const pushSubscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY, // Your VAPID public key }); setSubscription(pushSubscription); } }
VAPID kalitlarini yaratish uchun quyidagilarni bajaring:
npx web-push generate-vapid-keys
Bularning barchasini foydalanuvchi interfeysi uchun push-bildirishnomani sinab ko'rish funktsiyasi bilan birlashtirish
"use client"; import { useEffect, useState } from "react"; const Home = () => { const [subscription, setSubscription] = useState<PushSubscription | null>( null ); useEffect(() => { if ("serviceWorker" in navigator && "PushManager" in window) { registerServiceWorker(); } }, []); async function registerServiceWorker() { const registration = await navigator.serviceWorker.register("/sw.js", { //provide the route to the service worker scope: "/", updateViaCache: "none", }); const sub = await registration.pushManager.getSubscription(); if (sub) { setSubscription(sub); //This would be sent to a server } else { const pushSubscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY, // Your VAPID public key }); setSubscription(pushSubscription); } } //Create a function to test the notification const handleSendNotification = async () => { await fetch("/api/sendNotification", { method: "POST", body: JSON.stringify({ message: "Your timer has completed!", subscription: subscription, // This ideally, should not be included in the body. It should have already been saved on the server }), headers: { "Content-Type": "application/json", }, }); }; return ( <div> <h1>My PWA with Push Notifications</h1> <button onClick={handleSendNotification}>Notify Me!</button> </div> ); }; export default Home;
app
katalogida api
deb nomlangan yangi jild yarating.api
jildida sendNotification
nomli boshqa papka yarating.sendNotification
jildida route.ts
nomli fayl yarating.
Tuzilishi quyidagicha bo'lishi kerak
app/ └── api/ └── sendNotification/ └── route.ts
route.ts faylida quyidagi kod qatorlarini kiriting
import { NextResponse } from "next/server"; import webpush from "web-push"; webpush.setVapidDetails( "mailto:[email protected]", // Your email process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY!, process.env.VAPID_PRIVATE_KEY! ); export async function POST(req: Request) { const { message, subscription } = await req.json(); if (!subscription) { return NextResponse.json( { error: "No subscription available" }, { status: 400 } ); } try { await webpush.sendNotification( subscription, JSON.stringify({ title: "Notification", body: message }) ); return NextResponse.json({ success: true }); } catch (error) { console.error("Error sending notification:", error); return NextResponse.json( { error: "Failed to send notification" }, { status: 500 } ); } }
Ilova endi PWA ekanligini tasdiqlash uchun yuklab olish belgisi url satrining o'ng tomonida paydo bo'lishi kerak. Ilovalar ko'rinishida veb-manifest haqidagi ma'lumotlarni ham ko'rishingiz kerak.
Next.js-ning mahalliy PWA qo'llab-quvvatlashi bilan so'nggi yangilanishi progressiv veb-ilovalarni yaratish jarayonini juda muammosiz qildi. Next.js yordamida PWA-ni ishlab chiqish va joylashtirish zamonaviy veb-ishlab chiqishning bir qismi bo'lgan oddiy jarayon, chunki ishlab chiquvchilar endi veb-brauzer orqali foydalanuvchilar kutgan mahalliy xususiyatlarga ega ilovalarni tezda yaratishi mumkin.