Pages

How To Build Progressive Web Apps with Angular

Progressive web applications are a kind of web applications that are created with technologies to perform activities like native apps. The best part of progressive web apps is that it works efficiently when network coverage is not reliable. Plus, these web applications do not require installation like native apps, and these apps are efficient and faster than traditional native apps. 


In this article, we have mentioned steps to build progressive web apps with Angular and use Firebase to deploy the app.  


Prerequisites 

Before getting into the details of building progressive web apps, let's first see the environment you need to set up on your system. You can build a PWA app with Angular 14 or any other version of Angular. 



Now that we have taken care of the prerequisites, let’s dive into the steps that you need to follow for building a responsive PWA with Angular. 

Step 1: Create a new project

You first need to create a new project with Angular CLI. Angular by default generates test files that you will not need in creating a project. Hence use - -skip-tests flag in the following command. 


npx @angular/cli@10.0.0 new ng-pwa --skip-tests

 

This will prompt you with some configuration and the options are below. 


Output

? Would you like to add Angular routing? No

? Which stylesheet format would you like to use? CSS


A new project directory will be created named ng-pwa

Navigate it to another directory.


cd ng-pwa



You have successfully created a new project in Angular CLI.

Step 2: Create a Web Application Manifest

A web app manifest is a JASON file that includes a configuration that users can home save on their system’s home screen. The behavior and appearance will also be represented with it at the time of the home screen.  

In order to create a web app manifest for your application, use a new file name manifest.json in the src folder root.

nano src/manifest.json


Add the following code to the file.


{

   "name": "Angular Progressive Web App",

   "short_name": "Ng-PWA",

   "start_url": "./",

   "theme_color": "#008080",

   "background_color": "#008B8B",

   "display": "standalone",

   "description": "A PWA that is built with Angular",

   "icons": [

       {

           "src": "/assets/images/icons/icon-16x16.png",

           "sizes": "16x16",

           "type": "image/png"

       },

       {

            "src": "/assets/images/icons/icon-32x32.png",

            "sizes": "32x32",

            "type": "image/png"

        },

        {

            "src": "/assets/images/icons/icon-150x150.png",

            "sizes": "150x150",

            "type": "image/png"

        },

        {

            "src": "/assets/images/icons/icon-180x180.png",

            "sizes": "180x180",

            "type": "image/png"

        },

        {

            "src": "/assets/images/icons/icon-192x192.png",

            "sizes": "192x192",

            "type": "image/png"

        },

        {

            "src": "/assets/images/icons/icon-512x512.png",

            "sizes": "512x512",

            "type": "image/png"

        }

   ]

}



The above code is created in a way to support an app for different dimensions including mobile, tablet, and desktop. Therefore, make sure to add duplicate icons for different device sizes. 


After you have added images, visit index.file and add the below-given head section. 


...

<head>

  ...

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

  <meta name="theme-color" content="#008080">

</head>


The web app manifest will not be added automatically to the build folder until we ask Angular to do so. We will add ty to the build folder by adding manifest.json to the apps section of the assets array of .angular-cli.json file.


...

"apps": [

    {

     ...

      "assets": [

       ...

        "manifest.json"

      ],

...



In case you have to build your app with Angular 6 then you need to edit angular.json instead of the .angular-cli.json


...

"projects": {

  "ng-pwa": {

    ...

    "architect": {

      "build": {

        ...

        "assets": [

          "src/manifest.json"

        ],

...


Step 3: Add Service Workers

One of the foundation parameters for progressive web apps is service workers. It is written in JavaScript which helps cache necessary files and assets, which helps an app function at the time of network coverage unavailability. It can intercept requests and manages all the responses from the server. 


Build an app with webpack prior to production. Install the new package and configure it with npm package sw-precache-webpack-plugin 


Install the package by using the npm install command from the directory ng-pwa


npm install --save-dev sw-precache-webpack-plugin@1.0.0



Create a file called precache-config.js in the installed package. 


nano precache-config.js


Add up the below-given file


var SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');


module.exports = {

    navigateFallback: '/index.html',

    navigateFallbackWhitelist: [],

    stripePrefix: 'dist',

    root: 'dist/',

    plugins:[

        new SWPrecacheWebpackPlugin({

            cacheId: 'ng-pwa',

            filename: 'service-worker.js',

            staticFileGlobs: [

                'dist/index.html',

                'dist/**.js',

                'dist/**.css'

            ],


        })

    ],

    stripePrefix: 'dist/assets',

    mergeStaticsConfig: true

};




The sw-precache-webpack-plugin file is configured with precache-config.js file by using literal object-value pairs. 


Now to finish the Angular service worker environment set up in the system, create npm command or script which you can use to build an app and auto-generate the file of the service worker in the build folder. Add the following commands in package.json


...

 "scripts": {

    ...

    "pwa": "ng build --prod && sw-precache --root=dist --config=precache-config.js"

  },

 ...


Step 4: Create the View

Since we are creating a PWA Angular, we just need a single view. 

Edit the code app.component.html and replace it with new code. The following is the code you can use. 


<div class="container">

  <h1>

    A Progressive Web App Built with Angular.

  </h1>

  <img width="300" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOS4xLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiDQoJIHZpZXdCb3g9IjAgMCAyNTAgMjUwIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNTAgMjUwOyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCS5zdDB7ZmlsbDojREQwMDMxO30NCgkuc3Qxe2ZpbGw6I0MzMDAyRjt9DQoJLnN0MntmaWxsOiNGRkZGRkY7fQ0KPC9zdHlsZT4NCjxnPg0KCTxwb2x5Z29uIGNsYXNzPSJzdDAiIHBvaW50cz0iMTI1LDMwIDEyNSwzMCAxMjUsMzAgMzEuOSw2My4yIDQ2LjEsMTg2LjMgMTI1LDIzMCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAJIi8+DQoJPHBvbHlnb24gY2xhc3M9InN0MSIgcG9pbnRzPSIxMjUsMzAgMTI1LDUyLjIgMTI1LDUyLjEgMTI1LDE1My40IDEyNSwxNTMuNCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAxMjUsMzAgCSIvPg0KCTxwYXRoIGNsYXNzPSJzdDIiIGQ9Ik0xMjUsNTIuMUw2Ni44LDE4Mi42aDBoMjEuN2gwbDExLjctMjkuMmg0OS40bDExLjcsMjkuMmgwaDIxLjdoMEwxMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMQ0KCQlMMTI1LDUyLjF6IE0xNDIsMTM1LjRIMTA4bDE3LTQwLjlMMTQyLDEzNS40eiIvPg0KPC9nPg0KPC9zdmc+DQo=" alt="Angular logo">

  <h2>Get Started With Progressive Web Apps:</h2>

  <ul>

    <li>

      <h4><a target="_blank" rel="noopener" href="https://developers.google.com/web/fundamentals/primers/service-workers/">Service Workers</a></h4>

    </li>

    <li>

      <h4><a target="_blank" rel="noopener" href="https://developers.google.com/web/fundamentals/web-app-manifest/">Web App Manifest</a></h4>

    </li>

    <li>

      <h4><a target="_blank" rel="noopener" href="https://developers.google.com/web/fundamentals/codelabs/your-first-pwapp/">Code Lab (PWA)</a></h4>

    </li>

  </ul>

</div>



The above code builds a new web page including an image, three links, and some text. 


Now edit the styles.css and replace the code with the following. 


body {

    background-color: teal;

}


.container {

    text-align: center;

}


ul {

    list-style: none;

}


h1, h2, a {

    color: white;

}


Step 5: Deploy your Application

In order to make your app work properly, it is important to provide a secure connection. Therefore, we will be using Firebase to deploy our Angular app. 


  • Singin to Firebase Console and set up an environment. 

  • After signing in, click on the ‘Add project’ option to create a new project. 

  • You’ll be asked to enter the project’s name.


In this tutorial, we are only interested in the Hosting page and Develop section. Navigate back to the command terminal and run npm install in order to install the firebase-tools package. 


npm install -g firebase-tools@8.4.3


Now this package will enable us to test and deploy to Firebase from the terminal. 


Run the following command from the ng-pwa directory to create a PWA Angular app and auto-generate the service worker. 


npm run pwa


Below is the custom script that is generated prior to and created in our application production. 


                                          Source: digitalocean.com

Now run the below command and login to the Firebase. 


$ firebase login

 

Now enter your credentials like account information into the terminal. 


firebase init


Then answer the below questions as shown.


Are you ready to proceed? (Y/n) = Y

Which Firebase CLI features do you want to setup for this folder? = Hosting

Select a default Firebase project for this directory = Your-Firebase-Project-Name

What do you want to use as your public directory? = dist

Configure as a single-page app (rewrite all urls to /index.html)? (y/N) = Y

File dist/index.html already exists. Overwrite? (y/N) = N



                                            Source: digitalocean.com


Now run the following command to deploy the application as shown below. 


firebase deploy


Now the following app to see the application.


firebase open hosting:site


                                              Source: digitalocean.com

Troubleshooting

In case the ‘Firebase Hosting Setup Complete’ message pops up instead of your application, you might have overwritten your index.html. You need to rebuild with firebase init, npm run pwa and select the option ‘No’. 

Step 6: Lighthouse testing

Open the hosted app in your Google Chrome web browser to test your PWA. Lighthouse can be chosen by clicking the Extensions icon. You will see a popup and be asked to click the Generate report button. You will momentarily see a screen with the message "Waiting for Lighthouse results" after clicking the button. You will get a screen with the test results after it is finished. 


This Angular PWA example will help you build an interactive and secure web application with Angular. 


 


No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...