Progressive Web Apps (PWAs) offer a near-native app experience with web technologies. They are reliable, fast, and engaging. Here's how you can build a PWA using Aurelia 2 with TypeScript and Webpack.
Setting Up the Service Worker
The service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don't need a web page or user interaction. To create a PWA, we first need to set up a service worker.
Create a new file service-worker.ts in your src directory:
// src/service-worker.tsconstcacheName='aurelia-pwa-cache-v1';constfilesToCache= ['/','/index.html','/scripts/bundle.js',// Adjust with your actual app bundle files// Add other files you want to cache];self.addEventListener('install', (event:ExtendableEvent) => {event.waitUntil(caches.open(cacheName).then((cache) => {returncache.addAll(filesToCache); }) );});self.addEventListener('activate', (event:ExtendableEvent) => {event.waitUntil(caches.keys().then((keyList) => {returnPromise.all(keyList.map((key) => {if (key !== cacheName) {returncaches.delete(key); } })); }) );});self.addEventListener('fetch', (event:FetchEvent) => {event.respondWith(caches.match(event.request).then((response) => {return response ||fetch(event.request); }) );});
Registering the Service Worker
Now, we'll register the service worker in our Aurelia app.
Create a service worker registration file service-worker-registration.ts:
Update the webpack.config.js to include the service worker file in your build process. Make sure you install the workbox-webpack-plugin development dependency.
// webpack.config.jsconst { AureliaPlugin } =require('aurelia-webpack-plugin');constpath=require('path');const { GenerateSW } =require('workbox-webpack-plugin');module.exports= {// ... other configurations ... plugins: [newAureliaPlugin(),// ... other plugins ...newGenerateSW({ swDest:'service-worker.js', clientsClaim:true, skipWaiting:true, }) ],// ... other configurations ...};
Serve your dist directory using a static server that supports service workers (e.g., http-server).
Open your app in a browser, and use the Chrome DevTools to audit your app with Lighthouse.
Your Aurelia 2 app should now be a fully functioning PWA! Remember to update the list of files to cache in your service worker as your app grows and changes.