DEV Community

Cover image for ✨ How to make your React app a PWA with Create React App 4
Max Programming
Max Programming

Posted on • Updated on • Originally published at blog.usmans.me

✨ How to make your React app a PWA with Create React App 4

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
Enter fullscreen mode Exit fullscreen mode

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! ✌

Top comments (4)

Collapse
 
inezabonte profile image
Ineza Bonté Grévy

Which files does one save when caching the application in the assets

Collapse
 
maxprogramming profile image
Max Programming

Not sure because I am still learning about PWA and service workers.
This one is readymade by the create-react-app team

Collapse
 
inezabonte profile image
Ineza Bonté Grévy

For example if you have images you need to cache so that you don't have to fetch them from the server every time

Thread Thread
 
maxprogramming profile image
Max Programming

Maybe yes. It can maybe cache the images too. At once