Nextjs 和工作箱集成 [英] Nextjs and workbox integration
问题描述
要求:我正在尝试使用 Service Worker 并缓存静态文件,以便减少 HTTP 请求并提高站点性能.接下来我会切换到离线,缓存图像,api 等.
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.
我看过插件:
https://github.com/hanford/next-offline 和https://www.npmjs.com/package/next-pwa
似乎可以.虽然我试图找出是否有 (nextjs + workbox) 的例子.
It seems to work. Although I was trying to find out if there were examples of (nextjs + workbox).
Next js 确实有一个 https 的示例://github.com/vercel/next.js/tree/canary/examples/with-next-offline.但我只想为此使用工作箱.
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.
目前没有使用自定义服务器.只需使用 nextjs 的内置构建器(https://nextjs.org/docs/getting-开始#manual-setup)
Currently am not using a custom server. Just using the inbuilt builder of nextjs (https://nextjs.org/docs/getting-started#manual-setup)
推荐答案
我自己想出了一个答案:
I figured out an answer on my own:
参考:https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build#.generateSW我在这里为我的应用程序完成了运行时缓存并将工作箱文件添加到基本文件中:
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()
这篇关于Nextjs 和工作箱集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!