본문 바로가기
개발/Frontend

PWA 도입하기 - CRA 4.x 버전에서 PWA 도입하기

by lewns2 2023. 2. 4.

Progressive Web App (이하 PWA)?

PWA는 'Progressive Web App'의 줄인 말로, 모바일 사이트에서 네이티브 앱과 같은 사용자 경험을 제공하는 기술입니다.

즉, 웹 기술을 통해 모바일 앱과 같은 경험을 할 수 있게 합니다.

PWA는 서비스 워커 파일을 활성화시켜 서비스가 백그라운드에서 동작하게끔 만듭니다.

핵심은 이 서비스 워커란 녀석입니다. 서비스워커는 브라우저가 백그라운드에서 실행하는 스크립트이며 웹 페이지와 별개로 동작합니다.

서비스 워커에 대한 내용은 다음 글에서 살펴보도록 하고,

본 글에선 PWA 도입을 위한 서비스 워커 활성화 방법PWA로 구현할 수 있는 기능에 대해 살펴보겠습니다.

 

PWA로 무엇을 할 수 있을까?

앞서, PWA에 대한 설명 중 백그라운드라는 단어가 등장했습니다.

이러한 단어들과 함께 아래 제공하는 기능들을 본다면 더욱 쉽게 이해할 수 있으리라 생각합니다.

(여기서 말하는 백그라운드에 대한 정의는 사용자가 앱을 종료하거나, 다른 활동(탭)을 하는 경우를 뜻합니다.)

 

PWA에서 구현할 수 있는 기능은 다음과 같습니다.

  1. 푸시 알림
  2. 아이콘을 홈 화면에 추가(모바일)
  3. 오프라인에서 열람이 가능
  4. 표시속도의 고속화
  5. 검색 엔진 노출

 

PWA 도입 시, 주의할 점

PWA 도입을 위해선 SSL화가 필요합니다.

서비스 워커(Service Worker)는 보안 상의 이유로 HTTPS 프로토콜에서만 실행됩니다. (localhost는 가능합니다.)

 

프로젝트에 적용하기

PWA를 도입한다는 것은 '서비스 워커를 활성화 한다.' 라고 생각하시면 됩니다.
이미 React에서 PWA 적용을 위한 환경을 모두 제공해주고 있어 PWA를 적용하는 것은 어렵지 않습니다.

 

PWA로 프로젝트 생성

만약, 아직 프로젝트 생성 전이시라면 Making a Progressive Web App을 참고하여 바로 PWA 환경이 갖추어진 프로젝트를 생성하실 수 있습니다.

 

하지만, 이미 기존의 프로젝트가 있으신 분들이라면 간단한 작업이 필요합니다.

 

CRA(create-react-app)환경에서 적용하기

시작하기 앞서, CRA의 버전 확인이 필요합니다.

CRA 버전에 따라 기본으로 제공해주는 파일에 차이가 있어 적용 방법이 상이하기 때문입니다.

create-react-app 3.x.x 버전

3.x.x 버전까지는 서비스 워커 파일을 직접 제공합니다.

3.x.x 버전인 경우, 리액트 어플리케이션 생성 시, 아래와 같은 구조를 띄고 있을 것입니다.

├── README.md
├── node_modules
├── package.json
├── .gitignore
├── build
├── public
│   ├── favicon.ico
│   ├── index.html
│   └── manifest.json
└── src
    ├── App.css
    ├── App.js
    ├── App.test.js
    ├── index.css
    ├── index.js
    ├── logo.svg
    └── serviceWorker.js

서비스워커 파일이 존재하는 것을 확인할 수 있고, 이제 이를 등록하기만 하면 됩니다.
src/index.js

serviceWorker.unregister();

serviceWorker.register();

바꿔주시면 됩니다. 이제 서비스 워커를 사용할 준비를 마쳤습니다.

create-react-app 4.x.x 버전

CRA 버전이 업데이트되면서 이제 서비스 워커 파일을 별로 제공하지 않습니다.

그래서 4.x.x 버전인 경우, 리액트 어플리케이션 생성 시, 서비스 워커 파일을 찾아볼 수 없습니다.

 

그래서 우리는 별도로 새롭게 PWA 프로젝트를 생성한 후, service-worker.jsserviceWorkerRegistration.js 파일을 복사하여 가져와야합니다.

따라서, 새롭게 PWA 환경의 리액트 어플리케이션을 생성해줍니다.

npx create-react-app my-app --template cra-template-pwa

service-worker.jsserviceWorkerRegistration.js 파일을 복사하여 내가 적용하고자 하는 프로젝트에 가져옵니다.

파일 구조는 다음과 같습니다.

├── README.md
├── node_modules
├── package.json
├── .gitignore
├── build
├── public
│   ├── favicon.ico
│   ├── index.html
│   └── manifest.json
└── src
    ├── App.css
    ├── App.js
    ├── App.test.js
    ├── index.css
    ├── index.js
    ├── logo.svg
    └── service-worker.js
    └── serviceWorkerRegistration.js

 

마찬가지로, 이제 src/index.js에서 serviceWorkerRegistration.js를 불러와 등록을 해줍니다.

import * as serviceWorkerRegistration from './serviceWorkerRegistration';

...

serviceWorkerRegistration.register();

 

전체 파일은 다음과 같습니다.

src/service-worker.js

/* eslint-disable no-restricted-globals */

// This service worker can be customized!
// See https://developers.google.com/web/tools/workbox/modules
// for the list of available Workbox modules, or add any other
// code you'd like.
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.

import { clientsClaim } from "workbox-core";
import { ExpirationPlugin } from "workbox-expiration";
import { precacheAndRoute, createHandlerBoundToURL } from "workbox-precaching";
import { registerRoute } from "workbox-routing";
import { StaleWhileRevalidate } from "workbox-strategies";

clientsClaim();

// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST);

// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
const fileExtensionRegexp = new RegExp("/[^/?]+\\.[^/]+$");
registerRoute(
  // Return false to exempt requests from being fulfilled by index.html.
  ({ request, url }) => {
    // If this isn't a navigation, skip.
    if (request.mode !== "navigate") {
      return false;
    } // If this is a URL that starts with /_, skip.

    if (url.pathname.startsWith("/_")) {
      return false;
    } // If this looks like a URL for a resource, because it contains // a file extension, skip.

    if (url.pathname.match(fileExtensionRegexp)) {
      return false;
    } // Return true to signal that we want to use the handler.

    return true;
  },
  createHandlerBoundToURL(process.env.PUBLIC_URL + "/index.html")
);

// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
  // Add in any other file extensions or routing criteria as needed.
  ({ url }) =>
    url.origin === self.location.origin && url.pathname.endsWith(".png"), // Customize this strategy as needed, e.g., by changing to CacheFirst.
  new StaleWhileRevalidate({
    cacheName: "images",
    plugins: [
      // Ensure that once this runtime cache reaches a maximum size the
      // least-recently used images are removed.
      new ExpirationPlugin({ maxEntries: 50 }),
    ],
  })
);

// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener("message", (event) => {
  if (event.data && event.data.type === "SKIP_WAITING") {
    self.skipWaiting();
  }
});

// Any other custom service worker logic can go here.

src/serviceWorkerRegistration.js

// This optional code is used to register a service worker.
// register() is not called by default.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.

// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://cra.link/PWA

const isLocalhost = Boolean(
  window.location.hostname === "localhost" ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === "[::1]" ||
    // 127.0.0.0/8 are considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export function register(config) {
  if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebook/create-react-app/issues/2374
      return;
    }

    window.addEventListener("load", () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        // This is running on localhost. Let's check if a service worker still exists or not.
        checkValidServiceWorker(swUrl, config);

        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            "This web app is being served cache-first by a service " +
              "worker. To learn more, visit https://cra.link/PWA"
          );
        });
      } else {
        // Is not localhost. Just register service worker
        registerValidSW(swUrl, config);
      }
    });
  }
}

function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then((registration) => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (installingWorker == null) {
          return;
        }
        installingWorker.onstatechange = () => {
          if (installingWorker.state === "installed") {
            if (navigator.serviceWorker.controller) {
              // At this point, the updated precached content has been fetched,
              // but the previous service worker will still serve the older
              // content until all client tabs are closed.
              console.log(
                "New content is available and will be used when all " +
                  "tabs for this page are closed. See https://cra.link/PWA."
              );

              // Execute callback
              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a
              // "Content is cached for offline use." message.
              console.log("Content is cached for offline use.");

              // Execute callback
              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
    .catch((error) => {
      console.error("Error during service worker registration:", error);
    });
}

function checkValidServiceWorker(swUrl, config) {
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl, {
    headers: { "Service-Worker": "script" },
  })
    .then((response) => {
      // Ensure service worker exists, and that we really are getting a JS file.
      const contentType = response.headers.get("content-type");
      if (
        response.status === 404 ||
        (contentType != null && contentType.indexOf("javascript") === -1)
      ) {
        // No service worker found. Probably a different app. Reload the page.
        navigator.serviceWorker.ready.then((registration) => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl, config);
      }
    })
    .catch(() => {
      console.log(
        "No internet connection found. App is running in offline mode."
      );
    });
}

export function unregister() {
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker.ready
      .then((registration) => {
        registration.unregister();
      })
      .catch((error) => {
        console.error(error.message);
      });
  }
}

 

src/index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import * as serviceWorkerRegistration from "./serviceWorkerRegistration";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
serviceWorkerRegistration.register();

 

Service Worker 활성화 확인

그럼 이제 서비스워커가 활성화되었는 지, 확인해보겠습니다.

  1. 개발자도구(F12) → Application 탭 → Service Workers 클릭

위 사진과 같이 서비스 워커가 활성화된 모습을 볼 수 있습니다.

또, Lighthouse를 통해 PWA 적용에 필요한 내용을 확인하실 수 있습니다. 2. 개발자도구(F12) → Lighthouse 탭 → Progressive Web App 체크 → Generate report

 

 

로컬에서 확인하기

서비스 워커는 프로덕션 모드일 때만 활성화되기 때문에, 로컬 환경에서는 활성화 여부를 알 수 없습니다.
그래서 로컬에서 확인하기 위해, 리액트 애플리케이션을 프로덕션 버전으로 만들어 서빙합니다.

명령어는 아래와 같은 순서로 작성하시면 됩니다.

$ yarn global add serve
$ yarn build
$ serve -s build

마찬가지로 활성화 여부를 확인해보겠습니다.

  1. 개발자도구(F12) → Application 탭 → Service Workers 클릭



728x90
반응형

'개발 > Frontend' 카테고리의 다른 글

콜백함수  (0) 2023.02.06
[FE/Test] MSW에 대하여  (0) 2023.02.04