React - Can't find serviceWorker.js file in app src folder

Viewed 5350

I am new about react and I am following different tutorials trying to understand fundamentals. I'm using the v17 of react.

In those tutorials, I saw a file in the folder structure named serviceWorker.js that is used for making a progressive web app.

I generated my project with npx but in my folder structure, I can't find this file. Is it a bug? or is it something deprecated? or do I have to add it manually?

3 Answers

I ran into the same issue, I expected to find this in my index.js:

import * as serviceWorker from './serviceWorker';
serviceWorker.unregister();

I looked again at my index.js to see what create-react-app had configured and found:

import reportWebVitals from './reportWebVitals';
reportWebVitals();

This has replace serviceWorker in version 4 of CRA October 2020.

From CRA 4 you can either opt in by using cra-template-pwa or by creating your own src/service-worker.js file.

But seems you only need to do so if you want to opt-in for the offline/cache-first behavior. The rest of PWA of tools are included in CRA.

It is all explained in https://create-react-app.dev/docs/making-a-progressive-web-app

The way I solved it was by creating the project like this:

$npx create-react-app name-pwa --template cra-template-pwa

and in the file structure you will find the file service-worker.js and serviceWorkerRegistration.js

and now in your index.js just change unregister by register:

serviceWorkerRegistration.register();
Related