Search code examples
angular-service-worker

How to modify service worker file without overwriting it with ng build --prod


I want to update my service worker so I can receive notifications, the problem is every time I run ng build --prod it overwrites my files.

I created the service worker with the Angular CLI. If I understand it correctly I need to run the ng build --prod script to update the dist folder to deploy.

I update the ngsw-worker.js in the dist folder but it gets overwritten when I run the build command. I also have to add the Web.config manually to the dist folder everytime. How do take those changes with the build?


Solution

  • After your build you should copy in your own choice of ngsw-worker.js

    Note this will mean that your build will be unstable if angular-pwa is upgraded, you may not get bug fixes or other improvements as you're not updating "your" file".

    So include and install fs-extra:

    npm i fs-extra --save-dev
    

    The package should appear in your devDependencies:

    "fs-extra": "^8.0.1",
    

    Then you should copy your file in a script (save the script to a new dir) and call it move_file.js or similar:

    const fs = require('fs-extra');
    fs.copy('./src/app/my-ngsw-worker.js', './dist/ngsw-worker.js', err => {
      if (err) {
        return console.error(err)
      } else {
        console.log('success!')
      }
    });
    

    And finally call this after your ng build with an npm command: node scripts/move_file.js

    This will replace the generated one with your one.