[next.js]pwa缓存

[复制链接]
发表于 2024-6-14 21:35:57 | 显示全部楼层 |阅读模式
配置Next.js (v14+ App Router模式) 使其支持PWA缓存,配置server worker和mainfest.json,让项目支持离线访问和可安装。
安装依赖next-pwa
  1. npm i next-pwa
复制代码
配置next.config.js
  1. const path = require('path');
  2. const withPWAInit = require('next-pwa');
  3. // 判断环境
  4. const isProd = ['production'].includes(process.env.NODE_ENV);
  5. /** @type {import('next-pwa').PWAConfig} */
  6. const withPWA = withPWAInit({
  7.   dest: 'public',
  8.   disable: !isProd,
  9.   // Solution: https://github.com/shadowwalker/next-pwa/issues/424#issuecomment-1399683017
  10.   buildExcludes: ['app-build-manifest.json'],
  11. });
  12. const generateAppDirEntry = (entry) => {
  13.   const packagePath = require.resolve('next-pwa');
  14.   const packageDirectory = path.dirname(packagePath);
  15.   const registerJs = path.join(packageDirectory, 'register.js');
  16.   return entry().then((entries) => {
  17.     // Register SW on App directory, solution: https://github.com/shadowwalker/next-pwa/pull/427
  18.     if (entries['main-app'] && !entries['main-app'].includes(registerJs)) {
  19.       if (Array.isArray(entries['main-app'])) {
  20.         entries['main-app'].unshift(registerJs);
  21.       } else if (typeof entries['main-app'] === 'string') {
  22.         entries['main-app'] = [registerJs, entries['main-app']];
  23.       }
  24.     }
  25.     return entries;
  26.   });
  27. };
  28. /** @type {import('next').NextConfig} */
  29. const nextConfig = {
  30.         // ... 你的next.config配置项
  31.         ...
  32.         webpack: (config) => {
  33.             const entry = generateAppDirEntry(config.entry);
  34.                     config.entry = () => entry;
  35.             return config;
  36.           },
  37. }
  38. module.exports = withPWA(nextConfig);
复制代码
以上配置 我让其在生产情况主动创建server worker和workbox等文件并在欣赏器加载时初始化init sw文件,第二次访问时便可以创建sw缓存



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

© 2001-2025 Discuz! Team. Powered by Discuz! X3.5

GMT+8, 2025-7-15 06:23 , Processed in 0.073059 second(s), 30 queries 手机版|qidao123.com技术社区-IT企服评测▪应用市场 ( 浙ICP备20004199 )|网站地图

快速回复 返回顶部 返回列表