question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Registering the service-worker in dev mode.

See original GitHub issue

I just created the react-app by following the command:

create-react-app test

Now I want to play with service worker concepts in Dev mode. So I decided to write a simple service worker registration code over here:

export default function registerServiceWorker()
{
	 if('serviceWorker' in navigator) {
		navigator.serviceWorker.register(`${process.env.PUBLIC_URL}/service-worker.js`).then(function(register){
			console.log("worked", register);
		}).catch(function(err){
			console.log("error!")
		});
	}
}

And I registered by calling the function registerServiceWorker. Looks like the registration function works smoothly (as I could able to see the worked on the console log). However, I cannot see my real service-worker.js is called!

service-worker.js file looks like:

var cacheName = ‘helloWorld’;
self.addEventListener('install', event => { event.waitUntil(
	caches.open(cacheName).then(cache => cache.addAll([
		'/js/script.js',
		'/images/hello.png' ]))
	); 
});

But the caching is not working as I had given above in the code. Debugging shows that the service-worker.js file which is loaded by the browser something else. Not sure what mistake I’m making here. May be this is an issue?

Note I’m running the application using npm start

Thanks for the help.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:12 (3 by maintainers)

github_iconTop GitHub Comments

9reactions
antsmartiancommented, May 29, 2017

Ok thanks for the update. If one can’t play with service worker in Dev mode how one shall create them? I know in production mode out of box we get the service worker to cache static assets etc. But still I need to play in Dev mode as well. Let me know if there are any better way to handle them.

6reactions
nick-gaudreaucommented, Apr 29, 2018

Thanks @antoaravinth for bringing this up. Myself I just wanted to use SW first as a POC then possibly something to include in a presentation.

@redixhumayun if you’re still looking on how to do it in dev without changing the sw prod setup.

Create a simple sw register function in /src:

export default function LocalServiceWorkerRegister() {
    const swPath = `${process.env.PUBLIC_URL}/sw.js`;
    if ('serviceWorker' in navigator && process.env.NODE_ENV !== 'production') {
      window.addEventListener('load', function() {
        navigator.serviceWorker.register(swPath).then(function(registration) {
          // Registration was successful
          console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
          // registration failed :(
          console.log('ServiceWorker registration failed: ', err);
        });
      });
    }
}

Then in index.tsx import and call:

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import LocalServiceWorkerRegister from './sw-register';
//import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(
  <App />,
  document.getElementById('root') as HTMLElement
);

LocalServiceWorkerRegister();
//registerServiceWorker();

Then call your dev service worker file: sw.js (something different than prod) and put it in your /public folder.

npm start

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to use the service worker in dev mode with Create React ...
First add craco to the react project craco. then create custome craco plugin using below files. serviceWorkerRegistration.js
Read more >
ServiceWorkerRegistration - Web APIs | MDN
Chrome Edge ServiceWorkerRegistration Full support. Chrome40. Toggle history Full support. Edge... active Full support. Chrome40. Toggle history Full support. Edge... backgroundFetch. Experimental Full support. Chrome74. Toggle...
Read more >
Service worker registration - web.dev
Best practices for timing your service worker registration. ... in Incognito mode using network throttling to simulate a slow connection.
Read more >
Using Service Workers with create-react-app - Bits and Pieces
You can remove this condition from the function register() to enable it in development mode. · A cleaner way of enabling service workers...
Read more >
Create a Progressive Web App with React and Register a ...
[01:36] One really important thing to notice is that the service worker only registers in production mode. You could change this file to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found