将项目配置为pwa模式,就可以在浏览器里面看到安装应用的选项,并且可以将web网页像app一样添加到手机桌面或者pad桌面上,或者是电脑桌面上,这样带来的体验就像真的在一个app上运行一样。为了实现这个目的,我们可以为vue项目使用一个插件:vite-plugin-pwa
vite-plugin-pwa仓库地址:https://github.com/vite-pwa/vite-plugin-pwa
vite-plugin-pwa文档地址:Getting Started | Guide | Vite PWA
直接使用npm安装即可
npm i vite-plugin-pwa -D
# yarn
yarn add vite-plugin-pwa -D
# pnpm
pnpm add vite-plugin-pwa -D
先有一个pwa应用的图标,最好是png格式的,尺寸最好大于192x192的:
在vite.config.js/ts中配置pwa应用:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { VitePWA } from 'vite-plugin-pwa'
// 生产还是开发
const mode = 'production'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
VitePWA({
mode: 'development',
base: '/',
manifest: {
name: '应用名称',
short_name: '应用名称',
description: '应用描述',
icons: [
//添加图标, 注意路径和图像像素正确
{
src: './public/app.png',
sizes: '1024x1024',
type: 'image/png',
},
],
},
registerType: 'autoUpdate',
workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,jpg,svg}'], //缓存相关静态资源
runtimeCaching: [
// 配置自定义运行时缓存
mode !== 'production'
? {
urlPattern: ({ url }) =>
url.origin === 'https://app-api-0.com',
handler: 'NetworkFirst',
options: {
cacheName: 'wisbayar-api',
cacheableResponse: {
statuses: [200],
},
},
}
: {
urlPattern: ({ url }) =>
url.origin === 'https://app-api.id',
handler: 'NetworkFirst',
options: {
cacheName: 'wisbayar-api',
cacheableResponse: {
statuses: [200],
},
},
},
{
urlPattern: /\.(?:png|jpg|jpeg|svg)$/,
handler: 'CacheFirst',
options: {
cacheName: 'wisbayar-images',
expiration: {
// 最多30个图
maxEntries: 30,
},
},
},
{
urlPattern: /.*\.js.*/,
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'wisbayar-js',
expiration: {
maxEntries: 30, // 最多缓存30个,超过的按照LRU原则删除
maxAgeSeconds: 30 * 24 * 60 * 60,
},
cacheableResponse: {
statuses: [200],
},
},
},
{
urlPattern: /.*\.css.*/,
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'wisbayar-css',
expiration: {
maxEntries: 20,
maxAgeSeconds: 30 * 24 * 60 * 60,
},
cacheableResponse: {
statuses: [200],
},
},
},
{
urlPattern: /.*\.html.*/,
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'wisbayar-html',
expiration: {
maxEntries: 20,
maxAgeSeconds: 30 * 24 * 60 * 60,
},
cacheableResponse: {
statuses: [200],
},
},
},
],
},
devOptions: {
enabled: true,
},
}),
],
server: {
host: '0.0.0.0',
},
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
})
然后重新运行项目,就可以看到浏览器页面上有标识可以安装了:
如果想判断页面是不是在pwa中打开的,可以尝试使用:
const isInStandaloneMode = () =>
(window.matchMedia('(display-mode: standalone)').matches) || (window.navigator.standalone) || document.referrer.includes('android-app://');
if (isInStandaloneMode()) {
document.body.innerHTML = "是在pwa中打开的"
}else {
document.body.innerHTML = "请在pwa中打开"
}