Remove Service Worker - Gatsby
The Gatsby offline plugin is really handy right up until you don’t want it anymore!
I switched my main site over to Toast from Gatsby and hit a bump when it came to removing the old Gatsby site because it used a service worker meant that the new site had to remove the installed service worker.
How I got round it was taking the sw.js
file from the
gatsby-plugin-remove-service-worker
plugin and added that to the
build script of my new site.
A good place to start is if you have the offline plugin installed
already is to also have the gatsby-plugin-remove-service-worker
ready to go as well.
This is what my gatsby-config.js
looked like when I’d finished:
1// {2// resolve: `gatsby-plugin-offline`,3// options: {4// precachePages: [`/2020/*`, `/2021/*`],5// },6// },7`gatsby-plugin-remove-serviceworker`,8// {9// resolve: `gatsby-plugin-manifest`,10// options: {11// name: siteMetadata.title,12// short_name: siteMetadata.title,13// start_url: `/`,14// background_color: `#336699`,15// theme_color: `#663399`,16// display: `minimal-ui`,17// icon: `static/favicon.png`, // This path is relative to the root of the site.18// },19// },
So remove gatsby-plugin-offline
and gatsby-plugin-manifest
and
make sure gatsby-plugin-remove-serviceworker
is enabled.
If I go to https://scottspence.com/sw.js
I can see the script that
is in the gatsby-plugin-remove-serviceworker
package. What I need to
do now is mirror that on my new site.
Here’s that script:
1// sw.js2self.addEventListener('install', function (e) {3 self.skipWaiting()4})5
6self.addEventListener('activate', function (e) {7 self.registration8 .unregister()9 .then(function () {10 return self.clients.matchAll()11 })12 .then(function (clients) {13 clients.forEach(client => client.navigate(client.url))14 })15})
I’ve taken that sw.js
script from the
gatsby-plugin-remove-serviceworker
package and added it to the root
of my project.
I have a postbuild
script I run to create the sitemap and
robots.txt
file amongst other things so I’ll add it in with that.
In the npm
script I’ll move a copy of the sw.js
file to the
public
folder, that’s where the site build output goes:
1"sw": "cp sw.js public/"
Then when the new site spins up it will remove the old service worker.
Back to Top