DEV Community

loading...
Cover image for Don't struggle with extending the service worker in Create React App anymore. Upgrade to version 4!

Don't struggle with extending the service worker in Create React App anymore. Upgrade to version 4!

m3h0w profile image Michał Gacka Updated on ・2 min read

No need to struggle with how to customize and extend the service worker without ejecting Create React App anymore. Version 4, released in October 2020, comes with a service worker file available for extension in the src folder.

I wrote a post about the simplest way to extend the default service worker in CRA to help others who were dealing with this task. A strangely easy task requiring a dreadful amount of research and trial and error. But that was before I found out that there is an even simpler way: upgrading to the new CRA version.

The previous post generated some attention so I figured that I'm not the only one, who doesn't realize that one can now access the Service Worker file and edit it directly in the new CRA version.

Simply initialize the project with:
npx create-react-app my-app --template cra-template-pwa

or:
npx create-react-app my-app --template cra-template-pwa-typescript

And the service worker will be available for extension the src folder. Check out the official guide for more information and instructions.

Upgrading is quite straightforward too. I recommend creating the new project on the side, comparing the package.json files to update the old one, copying and merging the files generated in the src folder to the old project, and then fixing compile errors if any occur. It didn't take more than 20 minutes for my relatively large project.

Discussion (1)

pic
Editor guide
Collapse
khushalbhardwaj0111 profile image
Khushal Bhardwaj

I created a react app with create-react-app 4.1.0 but it doesn't generate a serviceworker in src, now i want to convert the react app into a pwa I created a worker.js in the public/
but to register the serviceworker in the src/index.js i want a serviceworker.js.

Any Insights regarding how to create a custom serviceworker file.