Add PWA to an Angular App
The Official Angular Docs make it seem very easy to convert an existing Angular App to a PWA. To demonstrate this, I'll show how it's possible to take the generic Angular CLI application that is built with ng new
and add PWA functionality to it (based on notes from the official Angular documentation).
First, start by creating a new Angular CLI project:
$ ng new <project-name>
$ cd <project-name>
Next, add the Angular PWA (Service Worker) functionality:
# long form docker command
docker run --rm -it -v $(pwd):/app angular-util:10.2.0 ng add @angular/pwa --project <project-name>
# or, with Angular CLI installed on your machine,
# or, with alias ng='docker run --rm -it -v $(pwd):/app angular-util:10.2.0 ng'
$ ng add @angular/pwa --project <project-name>
NOTE: If you are interested in learning more about the Docker Container that I'm using above (rather than installing the Angular CLI on your host machine), you can read my blog post about Docker Utility Containers.
Q?: In the ng add
command above, is --project <project-name>
really required?
Performing this step to a newly created (default) Angular application results in the following files being modified and created.
$ git s
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: angular.json
modified: package-lock.json
modified: package.json
modified: src/app/app.module.ts
modified: src/index.html
Untracked files:
(use "git add <file>..." to include in what will be committed)
ngsw-config.json
src/assets/icons/
src/manifest.webmanifest
Using a Dockerized Angular environment, this newly created PWA can then be built and served using the following commands:
# using long form
$ docker run --rm -it -v $(pwd):/app angular-util:10.2.0 ng build --prod
# or, with Angular CLI installed on your machine,
# or, using angular-cli specific alias
# with alias ng='docker run --rm -it -v $(pwd):/app angular-util:10.2.0 ng'
$ ng build --prod
# or, using generic angular-util image (NodeJS, Angular, npm, yarn, etc)
# with alias ngi='docker run --rm -it -v $(pwd):/app angular-util:10.2.0'
$ ngi ng build --prod
chunk {} runtime.acf0dec4155e77772545.js (runtime) 1.45 kB [entry] [rendered]
chunk {1} main.a2f2f2ba868f42fbe918.js (main) 225 kB [initial] [rendered]
chunk {2} polyfills.35a5ca1855eb057f016a.js (polyfills) 36 kB [initial] [rendered]
chunk {3} styles.09e2c710755c8867a460.css (styles) 0 bytes [initial] [rendered]
Date: 2020-11-22T22:50:56.978Z - Hash: 73ad25d26b84753bcc89 - Time: 22633ms
Finally, the PWA can be served via:
$ docker run --rm -it -v $(pwd)/dist/:/app -p 8080:8080 angular-util:10.2.0 npx http-server ./cli-spa/
Another important note about hosting PWAs is that they must be served over an HTTPS connection when deployed anywhere other than localhost
!