Setting up PWA with create-react-app and typescript.
Install create-react-app if you haven't already.
npm i create-react-app -g
Create a react app with TypeScript and PWA support. Also, we are using NPM as package manager. Alternatively, you may use yarn.
create-react-app frontend --use-npm --template cra-template-pwa-typescript
To build the project run:
npm run build
To run the build folder, we are using http-server. You may use any server.
Install http-server if you haven't already.
npm i http-server -D
Add script scripts section of package.json file:
"scripts": {
...
"start-sw": "http-server ./build"
}
To run the script, run:
npm run start-sw
Go to the browser and type the url with the associated port number.
To check the status of service workers, open chrome dev tools. Under the application section, go to "service workers" subsection.
If no service workers are registered, you need to enable them in the code.
Navigate to index.tsx and change serviceWorkerRegistration.unregister();
to serviceWorkerRegistration.register();
Rebuild the project and restart the server.
npm run build && npm run start-sw
Now you should see registered service workers.
You may also try stopping the server and reloading the site, or use chrome dev tools on Application section to simulate offline mode. Check the Offline checkbox on the Service workers section.
The site should reload without displaying a "No internet" error message.
Happy Hacking!
Top comments (0)