您的位置:首页 > 文旅 > 旅游 > [next.js]pwa缓存

[next.js]pwa缓存

2024/10/5 14:06:40 来源:https://blog.csdn.net/ZhuAiQuan/article/details/139470274  浏览:    关键词:[next.js]pwa缓存

配置Next.js (v14+ App Router模式) 使其支持PWA缓存,配置server worker和mainfest.json,让项目支持离线访问和可安装。

安装依赖next-pwa

npm i next-pwa

配置next.config.js

const path = require('path');const withPWAInit = require('next-pwa');// 判断环境
const isProd = ['production'].includes(process.env.NODE_ENV);/** @type {import('next-pwa').PWAConfig} */
const withPWA = withPWAInit({dest: 'public',disable: !isProd,// Solution: https://github.com/shadowwalker/next-pwa/issues/424#issuecomment-1399683017buildExcludes: ['app-build-manifest.json'],
});const generateAppDirEntry = (entry) => {const packagePath = require.resolve('next-pwa');const packageDirectory = path.dirname(packagePath);const registerJs = path.join(packageDirectory, 'register.js');return entry().then((entries) => {// Register SW on App directory, solution: https://github.com/shadowwalker/next-pwa/pull/427if (entries['main-app'] && !entries['main-app'].includes(registerJs)) {if (Array.isArray(entries['main-app'])) {entries['main-app'].unshift(registerJs);} else if (typeof entries['main-app'] === 'string') {entries['main-app'] = [registerJs, entries['main-app']];}}return entries;});
};/** @type {import('next').NextConfig} */
const nextConfig = {// ... 你的next.config配置项...webpack: (config) => {const entry = generateAppDirEntry(config.entry);config.entry = () => entry;return config;},
}module.exports = withPWA(nextConfig);

以上配置 我让其在生产环境自动创建server worker和workbox等文件并在浏览器加载时初始化init sw文件,第二次访问时便可以创建sw缓存
在这里插入图片描述
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com