Next.js 14 配置 PWA:打造渐进式 Web 应用的完整指南
前言
前面的文章中对 PWA 做了介绍,也介绍了它的交互流程。那么这里就对我开发的音乐网站做一个 PWA 配置,来实践一下 PWA 的配置过程。
操作环节
-
安装依赖
pnpm install next-pwa
-
然后就是之前文章提到的
Manifest
配置文件
新建配置文件/public/pwa/manifest.json
写入下面的内容{ "name": "音乐地带", "short_name": "music-web", "description": "一个免费听歌的地方", "start_url": "/", "display": "standalone", "background_color": "#ffffff", "theme_color": "#000000", "icons": [ { "src": "/icons/favicon.png", "sizes": "192x192", "type": "image/png" } ] }
这里注意的是图标,一定要存在且是
png
或者jpeg
的格式吧,反正.ico
我尝试不行。 -
之后在配置文件
next.config.mjs
中加入配置。如果你是.js 的后缀那么就使用require
和module.exports
代替import
和export
,模块语法的问题,常做前端开发的应该会明白。/** @type {import('next').NextConfig} */ import nextPWA from "next-pwa"; const withPWA = nextPWA({ dest: "public/pwa", disable: process.env.NODE_ENV === "development", // 开发环境中禁用 PWA register: true, skipWaiting: true, }); const nextConfig = withPWA({ // 你自己的其他配置 }); export default nextConfig;
-
在 head 中加入配置信息导入
打开你的app/layout.tsx
文件
添加上 meta 信息export const metadata = { title: "音乐地带", description: "一个免费听歌的地方", generator: "Next.js", manifest: "/pwa/manifest.json", keywords: ["music", "music-site"], themeColor: [{ media: "(prefers-color-scheme: dark)", color: "#fff" }], authors: [{ name: "David" }], viewport: "minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no, viewport-fit=cover", icons: [{ rel: "icon", url: "icons/favicon.png" }], };
再将 link 添加到 head 头部
<html lang={locale}>
// 就是这一段代码
<link rel="manifest" href="/pwa/manifest.json" />
<body
className={cn(
"h-dvh bg-background font-sans antialiased",
fontSans.variable
)}>
<HeaderBarWrapper>
{children} <Player />
</HeaderBarWrapper>
</body>
</html>
结尾
之后就可以执行 npm run build && npm start
然后打开网址,就可以在浏览器的搜索框里看到 下载应用的图标
。