DEV Community 👩‍💻👨‍💻

Cover image for Day 37 of #100DaysOfCode: PWA + SPA: initialize PWA on Create React App(CRA)
Jen-Hsuan Hsieh
Jen-Hsuan Hsieh

Posted on

Day 37 of #100DaysOfCode: PWA + SPA: initialize PWA on Create React App(CRA)

Introduction

The target of Progressive Web Apps(PWA) is to provide awesome experiences like native Apps. There are three main points for PWA.

  1. Reliable: they should load fast and even work if you're offline
  2. Fast: it should be able to access device features in an intuitive way
  3. Engaging: Feel like a native App on mobile devices

This article notes the initialization of PWA on the React App.

Steps

1. Create a React app

  • Use the following command to create a React app
create-react-app pwa-example
Enter fullscreen mode Exit fullscreen mode

2. Show hidden configure files

  • Use the following command to show hidden folders
npm run eject
Enter fullscreen mode Exit fullscreen mode
  • The config folder will show Alt Text

3. Edit src/index.js

Change the last line from

serviceWorker.unregister();
Enter fullscreen mode Exit fullscreen mode

to

serviceWorker.register();
Enter fullscreen mode Exit fullscreen mode

4. Generate files for production

  • Use the following command to build static files ad assets
npm run build
Enter fullscreen mode Exit fullscreen mode
  • It will generate the build folder with filed including service-worker.js Alt Text

5. Create a temporarily server to render pages

  • Use the following command to install serve and execute it to listen the build folder
npm install -g serve
serve -s build
Enter fullscreen mode Exit fullscreen mode
  • Serve will start to listen requests Alt Text

6.Validations

  • Open the browser and visit http://localhost:5000/
  • Open the developer tool and select Application/Service Workers
  • Check Offline and reload. The page should be rendered correctly. Alt Text

That's it!

References

Articles

There are some of my articles. Feel free to check if you like!

Top comments (0)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.