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
And that will generate two service worker files, one of them will be for the registration, and the other one the service worker itself.
index.js file, you'll get the import and the
.unregister() method as before
You can simply change the
.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.
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! ✌