DEV Community

Cover image for PWA with create-react-app
Peeyush Man Singh
Peeyush Man Singh

Posted on

PWA with create-react-app

Setting up PWA with create-react-app and typescript.

Install create-react-app if you haven't already.

npm i create-react-app -g
Enter fullscreen mode Exit fullscreen mode

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

To build the project run:

npm run build
Enter fullscreen mode Exit fullscreen mode

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

Add script scripts section of package.json file:

"scripts": {
    ...
    "start-sw": "http-server ./build"
}
Enter fullscreen mode Exit fullscreen mode

To run the script, run:

npm run start-sw
Enter fullscreen mode Exit fullscreen mode

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

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)