给Nextjs应用加入PWA支持

2022-07-23T14:30:56.242Z阅读110
3

什么是PWA

MDN官方的解释:PWA(Progressive Web Apps,渐进式 Web 应用)运用现代的 Web API 以及传统的渐进式增强策略来创建跨平台 Web 应用程序。这些应用无处不在、功能丰富,使其具有与原生应用相同的用户体验优势。这组文档和指南告诉您有关 PWA 的所有信息。

Next.js中,主要通过next-pwa来实现。

安装

pnpm add next-pwa

配置next.config.js


const withPWA = require('next-pwa')

const runtimeCaching = require('next-pwa/cache')


const nextConfig = withPWA({
  pwa: {
    dest: 'public',
    runtimeCaching,
    disable: process.env.NODE_ENV === 'development'
  },
})


module.exports = nextConfig

public目录下新增manifest.json和一个icon目录

关于manifest.json我这里直接献上源码,icon目录里面用来放下面代码中的图标。


{
  "name": "valnext",
  "short_name": "valnext",
  "theme_color": "#ffffff",
  "background_color": "#6768ab",
  "display": "fullscreen",
  "orientation": "portrait",
  "scope": "/",
  "start_url": "/",
  "icons": [
    {
      "src": "icons/icon-72x72.png",
      "sizes": "72x72",
      "type": "image/png",
      "purpose": "any maskable"
    },
    {
      "src": "icons/icon-96x96.png",
      "sizes": "96x96",
      "type": "image/png",
      "purpose": "any maskable"
    },
    {
      "src": "icons/icon-128x128.png",
      "sizes": "128x128",
      "type": "image/png",
      "purpose": "any maskable"
    },
    {
      "src": "icons/icon-144x144.png",
      "sizes": "144x144",
      "type": "image/png",
      "purpose": "any maskable"
    },
    {
      "src": "icons/icon-152x152.png",
      "sizes": "152x152",
      "type": "image/png",
      "purpose": "any maskable"
    },
    {
      "src": "icons/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png",
      "purpose": "any maskable"
    },
    {
      "src": "icons/icon-384x384.png",
      "sizes": "384x384",
      "type": "image/png",
      "purpose": "any maskable"
    },
    {
      "src": "icons/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png",
      "purpose": "any maskable"
    }
  ],
  "splash_pages": null
}

修改_app.tsxHead部分的代码

<Head>
  <title>valcosmos</title>
  <link rel="shortcut icon" href="webicon.ico"/>
  <meta
    name="description"
    content="description"
  />

  <meta
    name="keywords"
    content="HTML5, CSS3, JavaScript, TypeScript, Vue, React, 前端, 个人博客"
  />

  <meta name="author" content="author"/>

  <meta
    name="viewport"
    content="width=device-width,initial-scale=1.0,minimum-scale=1,maximum-scale=1,user-scalable=no"
  />

  <meta name="theme-color" content="#6768ab" />

  <link rel="manifest" href="/manifest.json" />

  <link
    href="/icons/icon-16x16.png"
    rel="icon"
    type="image/png"
    sizes="16x16"
  />
  <link
    href="/icons/icon-32x32.png"
    rel="icon"
    type="image/png"
    sizes="32x32"
  />

  <link rel="apple-touch-icon" href="/webicon.ico"></link>

</Head>

至此,大功告成。

这个我是在我的博客中进行的尝试,如果有小伙伴有兴趣,可以点击下面链接,查看源码。

https://github.com/valcosmos/valnext

如有未尽之处,还请大家多多包涵,希望这篇文章能帮到大家,感谢!

*邮箱为选填, 若输入邮箱,您留言的回复,将在第一时间以邮件的形式通知您。
总共0条留言
No Data