如何使用 Next.js 创建 PWA
大家好,
这篇文章是与James Q Quick合作的。如果你喜欢看视频,可以看看James Q Quick的这个视频。
那么让我们开始派对吧。
什么是 PWA?
PWA 是渐进式 Web 应用的缩写。它本质上就像一个用 HTML、CSS 和 JavaScript 构建的 Web 应用,并添加了以下一些功能:
- 极快
- 可安装
- 适用于所有浏览器
- 提供离线页面
- 推送通知
设置
创建 Next.js 应用
npx create-next-app next-pwa-demo
我将把默认的 Next.js 模板转换为 PWA,您可以转换您的 Web 应用程序。
安装所需的依赖项
npm i next-pwa # npm
yarn add next-pwa # yarn
生成清单
我将使用Simicart生成清单。您只需添加应用的详细信息,它就会生成清单。请确保standalone
在显示中选择
生成的清单将类似于此
{
"theme_color": "#000000",
"background_color": "#ffffff",
"display": "standalone",
"scope": "/",
"start_url": "/",
"name": "Next PWA",
"short_name": "PWA",
"description": "This app is to demo PWA in Next.js",
"icons": [
{
"src": "/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icon-256x256.png",
"sizes": "256x256",
"type": "image/png"
},
{
"src": "/icon-384x384.png",
"sizes": "384x384",
"type": "image/png"
},
{
"src": "/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
添加完所有详细信息后,安装并解压 zip 文件。解压后,将所有文件拖放到公共文件夹中。
我们将重命名manifest.webmanifest
为manifest.json
。
最后,公共目录应该如下所示
创建_document.js
在pages文件夹中创建_document.js
并添加以下一段代码
import Document, { Html, Head, Main, NextScript } from "next/document";
class MyDocument extends Document {
render() {
return (
<Html>
<Head>
<link rel="manifest" href="/manifest.json" />
<link rel="apple-touch-icon" href="/icon.png"></link>
<meta name="theme-color" content="#fff" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
在 Next config 中配置 PWA
我们需要添加一些数据来配置 PWA,因此请在中添加此代码片段next.config.js
。
const withPWA = require("next-pwa");
module.exports = withPWA({
pwa: {
dest: "public",
register: true,
skipWaiting: true,
},
});
你已经将你的应用变成了 PWA 🥳
营造更加优良的发展环境
将自动生成的文件添加到 .gitignore
如果您注意到的话,一些文件(例如服务工作者和工作箱)已被添加到公共文件夹中。
这些文件经常变化,但你的 GitHub 中并不需要它们。因此,请执行以下操作将它们从生产环境中移除。
-
删除
sw.js
、和。sw.js.map
workbox-****.js
workbox-****.js.map
-
将文件添加到
.gitignore
# PWA files
**/public/sw.js
**/public/workbox-*.js
**/public/worker-*.js
**/public/sw.js.map
**/public/workbox-*.js.map
**/public/worker-*.js.map
- 现在如果你重启服务器,文件名就会变暗
在开发中禁用 PWA
在开发中,您可能想要禁用 PWA,因为它会发出很多控制台消息。
我们将像这样禁用它next.config.js
const withPWA = require("next-pwa");
module.exports = withPWA({
pwa: {
dest: "public",
register: true,
skipWaiting: true,
disable: process.env.NODE_ENV === "development",
},
});
希望你觉得这篇文章有用。下期再见✌🏻
有用的链接-
文章来源:https://dev.to/avneesh0612/how-to-create-a-pwa-with-next-js-4dbm