โœจ How to make your React app a PWA with Create React App 4

โœจ How to make your React app a PWA with Create React App 4

ยท

3 min read

Welcome back developers ๐Ÿ‘‹.

Create React App or react-scripts is a great tool to scaffold out our React Apps. And one of the best parts of it was that we got a readymade serviceWorker.js file with it which would help us make the React app offline so easily.

But with the react-scripts version 4, whenever we use the command npx create-react-app app-name, we don't get the service worker file.

But no worries, we can easily generate a React App with the service worker file again, but we have to use a template. So instead of just running create-react-app, we should add a flag to it and this is how the new command looks like

Creating a new app

# JavaScript
npx create-react-app app-name --template cra-template-pwa

# TypeScript
npx create-react-app app-name --template cra-template-pwa-typescript

And that will generate two service worker files, one of them will be for the registration, and the other one the service worker itself.

image.png

In the index.js file, you'll get the import and the .unregister() method as before

image.png

image.png

You can simply change the .unregister() to .register() to register the service worker and now, when the app is built, it'll be capable to run offline. You'll see a button on the right side of your address bar if you are using Chrome or Edge or any other Chromium based browser.

image.png

On installing, it'll cache your app and it'll be able to run, even if you are online.

Converting an existing app

To convert an existing app, you can simply copy the code, create the required files and paste it from a gist that I created.

Also consider checking out the video on this topic if you want.

I hope this post helped you, make sure to ๐Ÿ’™ like it and share it to others.

๐Ÿ’ฌ Let me know your React apps which are PWAs in the comments.

Thanks for reading! โœŒ

Did you find this article valuable?

Support Usman Sabuwala by becoming a sponsor. Any amount is appreciated!