I know that we can test our service worker in production mode, but the proccess of re-building and deploying is quite annoying. Is there some way to enable serive worker in dev mode?
1 Answer
Change this
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
console.log("file location" + swUrl);
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
with this
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
console.log("file location" + swUrl);
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
});
in your serviceWorker.js file
also put replace this
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator ) {
with this
if ( 'serviceWorker' in navigator ) {
notice its checking for prod so removing that condition will start service worker on local also
3 Comments
Tạ Sinh Phúc
It worked but it didn't cache the static file like in production mode. I don't think
service-worker.js exists in dev modeHimanshuArora9419
All this will become tricky with default service worker. Will suggest you to right your own service worker either vanilla or with workbox.
karianpour
My problem is that the server does not return the service worker:
http://localhost:3000/service-worker.js return the index.html