I have added the @angular/pwa
package to my Angular CLI project with the command ng add @angular/pwa --project *project-name*
so it becomes a progressive web applicaiton, and this adds a service worker I know. I want to edit that default service worker to support e.g. handling Shared Targets links. I see that the service worker is registered to a file calleded ngsw-worker.js using the "Inspect" option in Google Chrome. How can I edit that service worker (ngsw-worker.js) created by the Angular CLI when compiled with ng build --prod
? What is the best way?
There are two ways you could do this. Get the ngsw-worker.js from the node_modules
folder, or get it in your output folder after building your app with ng build --prod
.
Copy the contents of the ngsw-worker.js into a new JavaScript file under e.g.: *MyProject*/src/service-worker.js
.
*MyProject*/src/angular.json
. Search for the "assets" key. There should be two. At the bottom of the array for each key, add your custom service worker file; e.g.: src/service-worker.js
so angular will include it.self.addEventLister('fetch', event => { ... })
at the top. That code adds a new event (it could be several of the same), so it won't overwrite anything... It could interfere with something else tho from the copied content of ngsw-worker.js.First build your app with ng build --prod
.
Now locate the location of the output folder ("outputPath" in angular.json
). In this example, it will be "../public".
Open a terminal to edit the file. I like to use VS Code; there is a terminal in there relative to my project folder installed through an extension.
Overwrite with your file with this command: cp public/service-worker.js public/ngsw-worker.js
.
Documents to learn more:
Note:
You should consider using the finished service worker given to you by @angular/service-worker
, with your custom code on top, which will be installed automatically when adding @angular/pwa
to your project and compiled with ng build --prod
.