LogoLogo
HomeDiscourseBlogDiscord
  • Introduction
  • Introduction
    • Quick start
    • Aurelia for new developers
    • Hello world
      • Creating your first app
      • Your first component - part 1: the view model
      • Your first component - part 2: the view
      • Running our app
      • Next steps
  • Templates
    • Template Syntax
      • Attribute binding
      • Event binding
      • Text interpolation
      • Template promises
      • Template references
      • Template variables
      • Globals
    • Custom attributes
    • Value converters (pipes)
    • Binding behaviors
    • Form Inputs
    • CSS classes and styling
    • Conditional Rendering
    • List Rendering
    • Lambda Expressions
    • Local templates (inline templates)
    • SVG
  • Components
    • Component basics
    • Component lifecycles
    • Bindable properties
    • Styling components
    • Slotted content
    • Scope and context
    • CustomElement API
    • Template compilation
      • processContent
      • Extending templating syntax
      • Modifying template parsing with AttributePattern
      • Extending binding language
      • Using the template compiler
      • Attribute mapping
  • Getting to know Aurelia
    • Routing
      • @aurelia/router
        • Getting Started
        • Creating Routes
        • Routing Lifecycle
        • Viewports
        • Navigating
        • Route hooks
        • Router animation
        • Route Events
        • Router Tutorial
        • Router Recipes
      • @aurelia/router-lite
        • Getting started
        • Router configuration
        • Configuring routes
        • Viewports
        • Navigating
        • Lifecycle hooks
        • Router hooks
        • Router events
        • Navigation model
        • Transition plan
    • App configuration and startup
    • Enhance
    • Template controllers
    • Understanding synchronous binding
    • Dynamic composition
    • Portalling elements
    • Observation
      • Observing property changes with @observable
      • Effect observation
      • HTML observation
      • Using observerLocator
    • Watching data
    • Dependency injection (DI)
    • App Tasks
    • Task Queue
    • Event Aggregator
  • Developer Guides
    • Animation
    • Testing
      • Overview
      • Testing attributes
      • Testing components
      • Testing value converters
      • Working with the fluent API
      • Stubs, mocks & spies
    • Logging
    • Building plugins
    • Web Components
    • UI virtualization
    • Errors
      • 0001 to 0023
      • 0088 to 0723
      • 0901 to 0908
    • Bundlers
    • Recipes
      • Apollo GraphQL integration
      • Auth0 integration
      • Containerizing Aurelia apps with Docker
      • Cordova/Phonegap integration
      • CSS-in-JS with Emotion
      • DOM style injection
      • Firebase integration
      • Markdown integration
      • Multi root
      • Progress Web Apps (PWA's)
      • Securing an app
      • SignalR integration
      • Strongly-typed templates
      • TailwindCSS integration
      • WebSockets Integration
      • Web Workers Integration
    • Playground
      • Binding & Templating
      • Custom Attributes
        • Binding to Element Size
      • Integration
        • Microsoft FAST
        • Ionic
    • Migrating to Aurelia 2
      • For plugin authors
      • Side-by-side comparison
    • Cheat Sheet
  • Aurelia Packages
    • Validation
      • Validation Tutorial
      • Plugin Configuration
      • Defining & Customizing Rules
      • Architecture
      • Tagging Rules
      • Model Based Validation
      • Validation Controller
      • Validate Binding Behavior
      • Displaying Errors
      • I18n Internationalization
      • Migration Guide & Breaking Changes
    • i18n Internationalization
    • Fetch Client
      • Overview
      • Setup and Configuration
      • Response types
      • Working with forms
      • Intercepting responses & requests
      • Advanced
    • Event Aggregator
    • State
    • Store
      • Configuration and Setup
      • Middleware
    • Dialog
  • Tutorials
    • Building a ChatGPT inspired app
    • Building a realtime cryptocurrency price tracker
    • Building a todo application
    • Building a weather application
    • Building a widget-based dashboard
    • React inside Aurelia
    • Svelte inside Aurelia
    • Synthetic view
    • Vue inside Aurelia
  • Community Contribution
    • Joining the community
    • Code of conduct
    • Contributor guide
    • Building and testing aurelia
    • Writing documentation
    • Translating documentation
Powered by GitBook
On this page
  • Setting Up the Service Worker
  • Registering the Service Worker
  • Webpack Configuration
  • Manifest File
  • Testing the PWA

Was this helpful?

Export as PDF
  1. Developer Guides
  2. Recipes

Progress Web Apps (PWA's)

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.ts

const cacheName = 'aurelia-pwa-cache-v1';
const filesToCache = [
  '/',
  '/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) => {
      return cache.addAll(filesToCache);
    })
  );
});

self.addEventListener('activate', (event: ExtendableEvent) => {
  event.waitUntil(
    caches.keys().then((keyList) => {
      return Promise.all(keyList.map((key) => {
        if (key !== cacheName) {
          return caches.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:

// src/service-worker-registration.ts

export function registerServiceWorker() {
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('service-worker.js').then((registration) => {
        console.log('SW registered: ', registration);
      }).catch((registrationError) => {
        console.log('SW registration failed: ', registrationError);
      });
    });
  }
}

Import and call this function in your main.ts:

// src/main.ts

import Aurelia, { RouterConfiguration } from 'aurelia';
import { MyApp } from './my-app';
import { registerServiceWorker } from './service-worker-registration';

Aurelia
  .register(RouterConfiguration)
  .app(MyApp)
  .start();

registerServiceWorker();

Webpack Configuration

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.js

const { AureliaPlugin } = require('aurelia-webpack-plugin');
const path = require('path');
const { GenerateSW } = require('workbox-webpack-plugin');

module.exports = {
  // ... other configurations ...
  plugins: [
    new AureliaPlugin(),
    // ... other plugins ...
    new GenerateSW({
      swDest: 'service-worker.js',
      clientsClaim: true,
      skipWaiting: true,
    })
  ],
  // ... other configurations ...
};

Manifest File

Create a manifest.json in your src directory:

// src/manifest.json

{
  "short_name": "Aurelia PWA",
  "name": "Aurelia Progressive Web App",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    },
    {
      "src": "logo192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "logo512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": ".",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}

Ensure that the manifest is copied to your dist directory during the build, and link it in your index.html:

<!-- index.html -->

<link rel="manifest" href="/manifest.json">

Testing the PWA

To test your PWA, you need to:

  • Run npm run build to create the production build.

  • 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.

PreviousMulti rootNextSecuring an app

Last updated 1 year ago

Was this helpful?