How to configure service workers with create-react-app

LilSap picture LilSap · Aug 6, 2016 · Viewed 20.7k times · Source

I am creating a ReactJS app with the create-react-app utility. How could I configure it to use a file that will contain a service worker?

EDIT: From Javascript side is clear for me, add the registration in my index.js:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('./service_workers/sw.js')
  .then(function(registration) {
    // Registration was successful...
  }).catch(function(err) {
    // registration failed ...
  });
}

Then my configuration in my service worker file (that for me is in service_wokers/sw.js):

self.addEventListener('install', function(event) {//my code here...});
self.addEventListener('activate', function(event) {//my code here...});
self.addEventListener('fetch', function(event) {//my code here...});

When I run this the console shows: ServiceWorker registration failed: DOMException: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.

The file is not there as I am not configuring Webpack to do that. So I am trying to copy the sw.js file with the ouput with:

test: 
     /\.(js)$/,
     loader: "file?name=[path][name].[ext]&context=./service_workers",
     include: '/service_worker'

I think there is no need to say that I am totally new to Webpack.

Answer

Ayesha Mundu picture Ayesha Mundu · Oct 17, 2019

for people who are still struggling on this. please refer https://create-react-app.dev/docs/making-a-progressive-web-app.

enter image description here

service workers are configured in CRA and will handle the caching for you! You just need to change :-

serviceWorker.unregister();

to

serviceWorker.register();

in your src/index.js file;

Also, service workers work on production mode only so make sure to build your application and serve it locally before testing your app for service workers.

npm i http-server -D

then add this to package.json, in your scripts.

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "start-sw": "http-server ./build"
}

now run :-

npm run build && npm run start-sw

hope it helps!