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.
In the index.js
file, you'll get the import and the .unregister()
method as before
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.
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)
Which files does one save when caching the application in the assets
Not sure because I am still learning about PWA and service workers.
This one is readymade by the
create-react-app
teamFor example if you have images you need to cache so that you don't have to fetch them from the server every time
Maybe yes. It can maybe cache the images too. At once