Skip to content

guide ionic pwa

devonfw-core edited this page Jan 5, 2022 · 18 revisions

Ionic Progressive Web App

This guide is a continuation of the guide Angular PWAs, therefore, valid concepts explained there are still valid in this page but focused on Ionic.

Assumptions

This guide assumes that you already have installed:

  • NodeJS

  • npm package manager

  • Angular CLI / Nx CLI

  • Ionic 5 CLI

  • Capacitor

Also, it is a good idea to read the document about PWA using Angular.

Sample Application

Ionic 5 PWA Base
Figure 1. Basic ionic PWA.

To explain how to build progressive web apps (PWA) using Ionic, a basic application is going to be built. This app will be able to take photos even without network using PWA elements.

Step 1: Create a new project

This step can be completed with one simple command: ionic start <name> <template>, where <name> is the name and <template> a model for the app. In this case, the app is going to be named basic-ion-pwa.

If you are using Nx, there is a pre-requisite to this step. And that is, you have to add the @nxtend/ionic-angular plugin to your Nx workspace. The command for that is npm install --save-dev @nxtend/ionic-angular. Once you have the plugin installed, you can generate an ionic app in your Nx workspace with the command nx generate @nxtend/ionic-angular:app basic-ion-pwa. (You can refer this guide if you want to get started with Nx).

Step 2: Structures and styles

The styles (scss) and structures (html) do not have anything specially relevant, just colors and ionic web components. The code can be found in devon4ts-samples.

Step 3: Add functionality

After this step, the app will allow users to take photos and display them in the main screen. First we have to import three important elements:

  • DomSanitizer: Sanitizes values to be safe to use.

  • SafeResourceUrl: Interface for values that are safe to use as URL.

  • Plugins: Capacitor constant value used to access to the device’s camera and toast dialogs.

import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { Plugins, CameraResultType } from '@capacitor/core';

The process of taking a picture is enclosed in a takePicture() method. takePicture() calls the Camera’s getPhoto() function which returns an URL or an exception. If a photo is taken then the image displayed in the main page will be changed for the new picture, else, if the app is closed without changing it, a toast message will be displayed.

export class HomePage {
  image: SafeResourceUrl;
  ...

  async takePicture() {
    try {
      const image = await Plugins.Camera.getPhoto({
        quality: 90,
        allowEditing: true,
        resultType: CameraResultType.Uri,
      });

      // Change last picture shown
      this.image = this.sanitizer.bypassSecurityTrustResourceUrl(image.webPath);
    } catch (e) {
      this.show('Closing camera');
    }
  }

  async show(message: string) {
    await Plugins.Toast.show({
      text: message,
    });
  }
}

Step 4: PWA Elements

When Ionic apps are not running natively, some resources like Camera do not work by default but can be enabled using PWA Elements. To use Capacitor’s PWA elements run npm install @ionic/pwa-elements and modify src/main.ts as shown below.

...

// Import for PWA elements
import { defineCustomElements } from '@ionic/pwa-elements/loader';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

// Call the element loader after the platform has been bootstrapped
defineCustomElements(window);

Step 5: Make it Progressive.

Turning an Ionic 5 app into a PWA is pretty easy. The same module used to turn Angular apps into PWAs has to be added. To do so, run: ng add @angular/pwa. This command also creates an icons folder inside src/assets and contains angular icons for multiple resolutions. (Note: In an Nx workspace, you have to add it like a normal package using npm install @angular/pwa, and you have to manually add the icons). If you want to use other images, be sure that they have the same resolution, the names can be different but the file manifest.json has to be changed accordingly.

Step 6: Configure the app

manifest.json

Default configuration.

ngsw-config.json

At assetGroupsresources add a URLs field and a pattern to match PWA Elements scripts and other resources (images, styles, …​):

"urls": ["https://unpkg.com/@ionic/pwa-elements@1.0.2/dist/**"]

Step 7: Check that your app is a PWA

To check if an app is a PWA lets compare its normal behavior against itself but built for production. Run in the project’s root folder the commands below:

ionic build --configuration production to build the app using production settings. (nx build basic-ion-pwa --configuration production in your Nx workspace root).

npm install http-server to install an npm module that can serve your built application. Documentation here. A good alternative is also npm install serve. It can be checked here.

Go to the www folder running cd www.

http-server -o or serve to serve your built app.

ℹ️
In order not to install anything not necessary npx can be used directly to serve the app. i.e run npx serve [folder] will automatically download and run this HTTP server without installing it in the project dependencies.
Http server running
Figure 2. Http server running on localhost:8081.

 
In another console instance run ionic serve (nx serve basic-ion-pwa if using Nx CLI) to open the common app (not built).

Ionic serve on Visual Studio Code console
Figure 3. Ionic server running on localhost:8100.

 
The first difference can be found on Developer tools → application, here it is seen that the PWA application (left) has a service worker and the common one does not.

Application comparison
Figure 4. Application service worker comparison.

 
If the "offline" box is checked, it will force a disconnection from network. In situations where users do not have connectivity or have a slow, one the PWA can still be accessed and used.

Online offline apps
Figure 5. Offline application.

 
Finally, plugins like Lighthouse can be used to test whether an application is progressive or not.

Lighthouse report
Figure 6. Lighthouse report.
Clone this wiki locally