首页 > 解决方案 > 如何使用 next-pwa 预缓存所有页面

问题描述

我将如何使用 预缓存我的nextjs应用程序的所有页面next-pwa?假设我有以下页面:

我希望所有这些都被预先缓存,以便在第一次加载应用程序后它们都可以离线使用。目前我正在使用自定义 webpack 配置将.next/build-manifest.json文件复制到public/build-manifest. 然后,一旦应用程序第一次加载,我注册一个activated处理程序来获取build-manifest.json文件,然后将它们添加到缓存中。它有效,但似乎是一种迂回的实现方式,并且在某种程度上取决于实现细节。我将如何以更规范的方式完成相同的任务?

目前,我的next.config.js文件看起来像这样

const pwa = require('next-pwa')
const withPlugins = require('next-compose-plugins')
const WebpackShellPlugin = require('webpack-shell-plugin-next')

module.exports = withPlugins([
  [
    {
      webpack: (config, { isServer }) => {
        if (isServer) {
          config.plugins.push(
            new WebpackShellPlugin({
              onBuildExit: {
                scripts: [
                  'echo "Transfering files ... "',
                  'cp -r .next/build-manifest.json public/build-manifest.json',
                  'echo "DONE ... "',
                ],
                blocking: false,
                parallel: true,
              },
            })
          )
        }

        return config
      },
    },
  ],
  [
    pwa,
    {
      pwa: {
        dest: 'public',
        register: false,
        skipWaiting: true,
      },
    },
  ],
])

我的服务人员钩子看起来像这样

import { useEffect } from 'react'
import { Workbox } from 'workbox-window'

export function useServiceWorker() {
  useEffect(() => {
    if (
      typeof window !== 'undefined' &&
      'serviceWorker' in navigator &&
      (window as any).workbox !== undefined
    ) {
      const wb: Workbox = (window as any).workbox

      wb.addEventListener('activated', async (event) => {
        console.log(`Event ${event.type} is triggered.`)
        console.log(event)

        const manifestResponse = await fetch('/build-manifest.json')
        const manifest = await manifestResponse.json()

        const urlsToCache = [
          location.origin,
          ...manifest.pages['/[[...params]]'].map(
            (path: string) => `${location.origin}/_next/${path}`
          ),

          `${location.origin}/about`,
          ...manifest.pages['/about'].map((path: string) => `${location.origin}/_next/${path}`),

          `${location.origin}/posts`,
          ...manifest.pages['/posts'].map((path: string) => `${location.origin}/_next/${path}`),
        ]

        // Send that list of URLs to your router in the service worker.
        wb.messageSW({
          type: 'CACHE_URLS',
          payload: { urlsToCache },
        })
      })

      wb.register()
    }
  }, [])
}

任何帮助是极大的赞赏。谢谢。

标签: next.jsnext-pwa

解决方案


推荐阅读