Nextjs and workbox integration

浪子不回头ぞ 提交于 2021-01-04 05:41:22

问题


Requirement: I am trying to use service worker and cache static files so as to have a benefit to reduce HTTP requests and make the site performance better.  Down the lane I would switch to offline, caching images, api's etc.

I have seen the plugins:

https://github.com/hanford/next-offline and https://www.npmjs.com/package/next-pwa

It seems to work. Although I was trying to find out if there were examples of (nextjs + workbox).

Next js do have an example for https://github.com/vercel/next.js/tree/canary/examples/with-next-offline. But I would like just using workbox for this.

Anyone got any working examples? Even a basic one would do.

Currently am not using a custom server. Just using the inbuilt builder of nextjs (https://nextjs.org/docs/getting-started#manual-setup)


回答1:


I figured out an answer on my own:

Reference: https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build#.generateSW I have done runtime caching for my app here and added the workbox file into the base file:

 // Use the window load event to keep the page load performant
useEffect(() => {
   window.addEventListener("load", () => {
        const serviceWorkerScope = `/${country}/workbox-worker.js`
        navigator.serviceWorker
          .register(serviceWorkerScope)
          .then(() => {
            logger.info(`Service worker registered at ${serviceWorkerScope}`)
          })
          .catch(error => {
            logger.error("Error in serviceWorker registration: ", error)
          })
      })
})
   
I have added comments,

    // File to generate the service worker.
    require("dotenv").config()
    const workboxBuild = require("workbox-build")
    const { COUNTRY: country, NODE_ENV } = process.env
    const urlPattern = new RegExp(`/${country}\/static|_next\/.*/`)
    
    // https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build#.generateSW
    const buildSW = () => {
      return workboxBuild.generateSW({
        swDest: "public/workbox-worker.js",
        clientsClaim: true,
        mode: NODE_ENV,
        skipWaiting: true,
        sourcemap: false,
        runtimeCaching: [
          {
            urlPattern: urlPattern,
    
            // Apply a cache-first strategy.
            handler: "CacheFirst",
            options: {
              cacheName: "Static files caching",
              expiration: {
                maxEntries: 50,
                maxAgeSeconds: 15 * 60, // 15minutes
              },
            },
          },
        ],
      })
    }
    
    buildSW()



来源:https://stackoverflow.com/questions/63841653/nextjs-and-workbox-integration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!