nextjs: next-pwa/sw/workbox/pwa 使用
在 next.js 中使用 pwa,使用 next-pwa 这个库
01 安装 next-pwa
安装 next-pwa
# 添加 next-pwa
yarn add --dev next-pwa
# 添加 sw-updater
yarn add @jswork/react-sw-updater
02 修改 next.config.ts
修改配置 next.config.ts
import type { NextConfig } from 'next';
import nextPWA from 'next-pwa';
const nextConfig = {} as NextConfig;
const withPWA = nextPWA({
dest: 'public',
buildExcludes: ['app-build-manifest.json', 'dynamic-css-manifest.json']
})(nextConfig);
export default withPWA;
03 添加 page-checker 逻辑
添加 shared/components/page-checker.tsx
,代码如下
/**
* @Author: aric 1290657123@qq.com
* @Date: 2025-01-04 21:48:29
* @LastEditors: aric 1290657123@qq.com
* @LastEditTime: 2025-01-04 22:42:10
*/
'use client';
import ReactSwUpdater from '@jswork/react-sw-updater';
const Anonymous = () => {
return (
<ReactSwUpdater
interval={5 * 1000}
disabled={process.env.NODE_ENV !== 'production'}
onChange={({ update }) => {
update().then((res) => {
console.log('Success updated', res);
});
}}
/>
);
};
export default Anonymous;
04 在 app 中的 layout.tsx
修改 app/layout.tsx
import type { Metadata } from 'next';
import { Geist, Geist_Mono } from 'next/font/google';
import './globals.css';
import PageChecker from '@/shared/components/page-checker';
const geistSans = Geist({
variable: '--font-geist-sans',
subsets: ['latin']
});
const geistMono = Geist_Mono({
variable: '--font-geist-mono',
subsets: ['latin']
});
export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app'
};
export default function RootLayout({
children
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
{children}
<PageChecker />
</body>
</html>
);
}
05 添加 .gitignore
添来看看 sw.js
的生成文件到 .gitignore
列表中
# next-pwa
public/sw.js
public/workbox-*.js
## editors
.idea
.vscode