配置Next.js (v14+ App Router模式) 使其支持PWA缓存,配置server worker和mainfest.json,让项目支持离线访问和可安装。
安装依赖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缓存


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