Search code examples
angular-cliservice-workerangular-service-worker

How to edit your service worker file for an Angular CLI project


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?


Solution

  • Get the current Service Worker:

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

    2. Copy the contents of the ngsw-worker.js into a new JavaScript file under e.g.: *MyProject*/src/service-worker.js.

    Make Angular CLI include your file on compilation:

    1. Go into *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.

    Edit the Service Worker:

    1. Now you can edit your custom service worker file as you want. E.g.: add 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.

    Final Step - Add the Service Worker:

    1. First build your app with ng build --prod.

    2. Now locate the location of the output folder ("outputPath" in angular.json). In this example, it will be "../public".

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

    4. Overwrite with your file with this command: cp public/service-worker.js public/ngsw-worker.js.

    Thats it!

    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.