配置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-1399683017
buildExcludes: ['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/427
if (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缓存
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » [next.js]pwa缓存
发表评论 取消回复