두 번째 PWA(Progressive Web App)를 구축한 방법

11783 단어 showdevwebdevtutorial
이 게시물은 원래 silvestar.codes에 게시되었습니다.

현재 내 사이드 ​​프로젝트Code Line Daily는 프로그레시브 웹 앱으로 제공됩니다.

를 읽으셨다면 이 글은 속편입니다.

연장 상자



PWA를 만들려는 이전 시도에서는 모든 것을 수동으로 처리했습니다. 사용 가능한 옵션과 기술에 대해 배웠고 PWA 웹 사이트의 작동 방식을 이해하는 데 도움이 되었습니다.

이번에는 PWA를 만들기 위해 Workbox을 사용하기로 했습니다. Workbox는 PWA를 보다 원활하게 만들기 위한 Google의 도구입니다.

Workbox is a set of libraries and Node modules that make it easy to cache assets and take full advantage of features used to build Progressive Web Apps.



내가 몇 분 만에 초기 버전을 설정하고 설정한 우수“Getting Started” guide가 있습니다. Workbox가 "CacheFirst"또는 "StaleWhileRevalidate"와 같은 기능을 제공합니다predefined caching strategies. 다음과 같이 한 줄로 캐싱 전략을 설정할 수 있습니다.

// Serve all CSS files with StaleWhileRevalidate strategy
workbox.routing.registerRoute(
  /\.css$/,
  new workbox.strategies.StaleWhileRevalidate()
)


이 전략은 가능한 경우 오래된/오래된 CSS 파일을 제공하는 것을 알려줍니다. 사용할 수 없는 경우 네트워크 요청을 사용하여 파일을 가져옵니다.

Code Line Dailyin the GitHub repository의 모든 전략을 볼 수 있습니다.

사전 캐싱



전략을 설정한 후 Workbox CLI을 사용하여 미리 캐시할 파일 목록을 만들었습니다. Workbox CLI를 전역npm 패키지로 설치했습니다.

npm i -g workbox-cli


그 후 내 터미널에서 workbox 명령을 사용할 수 있었습니다. 마법사를 불러오는 명령을 실행했습니다.

workbox wizard --injectManifest


구성된 경로를 선택하고 사전 캐시할 파일을 선택했으며 Workbox CLI에서 새 파일을 생성했습니다.

파일을 Service Worker 파일에 삽입할 수 있도록 다음 줄을 추가했습니다.

workbox.precaching.precacheAndRoute([]);


마지막으로 미리 캐시할 파일 목록이 채워진 새 서비스 작업자 파일을 생성하는 명령workbox injectManifest을 실행했습니다.

오토메이션



나는 모든 것이 잘 돌아가고 있어서 매우 기뻤지만 이 명령을 수동으로 실행해야 한다는 것을 깨달았습니다. 이미 이 프로젝트를 자동화하기 위해 많은 노력을 기울였기 때문에 Gulp 작업에 Workbox를 추가하고 싶었습니다. 다행스럽게도 Workbox는 Node.js 환경용 플러그인으로도 사용할 수 있습니다.

내 필요에 맞는 논리적 옵션처럼 보이는 사전 캐싱 설정으로 서비스 작업자를 생성하는 generateSW 모드가 있습니다.

This will generate a service worker with precaching setup for all of the files picked up by your configuration.



다음은 내 프로젝트의 구성입니다.

{
  "globDirectory": "dist/",
  "globPatterns": [
    "**/*.{html,webmanifest,css,eot,svg,ttf,woff,woff2,png,js,ico,jpg}"
  ],
  "globIgnores": [
    "docs/**/*",
    "gfx/cover/**/*"
  ],
  "swDest": "dist/sw.js",
  "swSrc": "src/sw/sw.js"
}


어디:
  • swSrc 옵션은 서비스 작업자 파일을 찾을 위치를 알려줍니다.
  • swDest 옵션은 처리된 서비스 작업자 파일을 저장할 위치를 알려줍니다.
  • globDirectory 옵션은 미리 캐시된 파일을 검색할 폴더를 지정합니다.
  • globPatterns 옵션은 사용할 패턴을 알려주고
  • globIgnores 옵션은 패턴 일치에도 불구하고 무시할 폴더를 알려줍니다.

  • Gulp 작업을 실행한 후 다음과 같은 최종 Service Worker 파일을 얻었습니다.

    // load workbox
    importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js')
    
    // output successful message
    if (workbox) {
      console.log(`Yay! Workbox is loaded 🎉`)
    } else {
      console.log(`Boo! Workbox didn't load 😬`)
    }
    
    workbox.core.setCacheNameDetails({
      prefix: 'cld',
      suffix: 'v1.0',
      precache: 'precache',
      runtime: 'runtime'
    })
    
    workbox.precaching.precacheAndRoute([
      // precached file list
    ])
    
    // Serve all html files with StaleWhileRevalidate strategy
    workbox.routing.registerRoute(
      /\.html$/,
      new workbox.strategies.NetworkFirst()
    )
    
    // Serve all css files with StaleWhileRevalidate strategy
    workbox.routing.registerRoute(
      /\.js$/,
      new workbox.strategies.StaleWhileRevalidate()
    )
    
    // Serve all css files with StaleWhileRevalidate strategy
    workbox.routing.registerRoute(
      /\.css$/,
      new workbox.strategies.StaleWhileRevalidate()
    )
    
    // Serve all other assets with CacheFirst strategy
    workbox.routing.registerRoute(
      /\.(?:png|jpg|jpeg|svg|gif|webp|ico|webmanifest|eot,ttf,woff,woff2)$/,
      new workbox.strategies.CacheFirst({
        plugins: [
          new workbox.expiration.Plugin({
            maxEntries: 20,
            maxAgeSeconds: 30 * 24 * 60 * 60
          })
        ]
      })
    )
    
    


    최종 결과



    Code Line Daily는 이제 Progressive Web App입니다. 이것이 저의 두 번째 PWA이며 모든 사람이 이에 대해 자세히 알아보도록 권하고 싶습니다. 이제 사이트를 오프라인에서 사용할 수 있지만 가능할 때마다 캐시된 자산을 제공하여 사용자의 대역폭도 절약하고 있습니다. 계속해서 Code Line Daily을 설치하고 어떻게 생각하는지 알려주세요.

    Lighthouse showing fireworks for perfect scores.

    보너스 포인트로 Code Line Daily 사이트에 대한 감사를 실행했는데 my personal site 에서처럼 불꽃놀이가 다시 보입니다. 💯

    좋은 웹페이지 즐겨찾기