配置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缓存