vite-plugin-pwa配置详解

news/2024/4/28 10:38:51/文章来源:https://blog.csdn.net/YMX2020/article/details/130882745

vite-plugin-pwa配置详解

前提:前端域名和后端服务域名相同时,用window.open新开页面下载或者导出文件,项目中导出和下载功能失效,原因是,域名相同走缓存

实现service worker离线缓存以前需要自己编写sw.js文件内容,比较复杂。 谷歌提供了workbox-*库来协助写配置。
vite-plugin-pwa就是帮你使用workbox结合一些模板代码自动生成sw.js,实现0配置

一:vite-plugin-pwa的简单使用
  • 默认缓存所有的js.css.html
// vite.config.ts/js
import { VitePWA } from "vite-plugin-pwa";
export default {plugins: [VitePWA()]
}
二:先看VitePWAOptions的配置
function VitePWA(userOptions?: Partial<VitePWAOptions>): Plugin[];
interface VitePWAOptions {// @default process.env.NODE_ENV or "production"mode?: 'development' | 'production';// @default 'public'srcDir?: string;// @default 'dist'outDir?: string;// @default 'sw.js'filename?: string;// @default 'manifest.webmanifest'manifestFilename?: string;// @default 'generateSW'strategies?: 'generateSW' | 'injectManifest';// @default same as `base` of Vite's configscope?: string;//`inline` - inject a simple register, inlined with the generated html//`script` - inject <script/> in <head>, with the `sr` to a generated simple register//`null` - do nothing, you will need to register the sw you self, or imports from `virtual:pwa-register`// @default 'auto'injectRegister: 'inline' | 'script' | 'auto' | null | false;// `prompt` - you will need to show a popup/dialog to the user to confirm the reload.// `autoUpdate` - when new content is available, the new service worker will update caches and reload all browser// @default 'prompt'registerType?: 'prompt' | 'autoUpdate';// @default trueminify: boolean;manifest: Partial<ManifestOptions> | false;// @default falseuseCredentials?: boolean;workbox: Partial<GenerateSWOptions>;injectManifest: Partial<CustomInjectManifestOptions>;// @default "base" options from Vitebase?: string;includeAssets: string | string[] | undefined;// @default trueincludeManifestIcons: boolean;// @default falsedisable: boolean;devOptions?: DevOptions;// @default falseselfDestroying?: boolean;
}

这里只重点介绍几个配置,其他感兴趣的自行查阅文档:

  • . strategies: 默认是generateSW然后去配置workbox;,如果你需要更多自定义的设置,可以选择injectManifest,那就对应配置injectManifest
  • . workbox: 是对应generateSW的配置,所有的workbox配置,最终将生成`sw.js文件

在这里插入图片描述

三:再看workbox的类型----GenerateSWOptions
type GenerateSWOptions = BasePartial & GlobPartial & GeneratePartial & RequiredSWDestPartial & OptionalGlobDirectoryPartial;
export interface GlobPartial {/*** A set of patterns matching files to always exclude when generating the* precache manifest. For more information, see the definition of `ignore` in* the `glob` [documentation](https://github.com/isaacs/node-glob#options).* @default ["**\/node_modules\/**\/*"]*/globIgnores?: Array<string>;/*** Files matching any of these patterns will be included in the precache* manifest. For more information, see the* [`glob` primer](https://github.com/isaacs/node-glob#glob-primer).* @default ["**\/*.{js,css,html}"]*/globPatterns?: Array<string>;
}

重点关注:

  • globPatterns: 最开始我们说配置会默认缓存所有的js.css.html,我是就是通过globPatterns实现的。如果想增加图片缓存可以在里面添加
  • globIgnores: 忽略不想缓存的资源
export interface GeneratePartial {/*** Any search parameter names that match against one of the RegExp in this* array will be removed before looking for a precache match. This is useful* if your users might request URLs that contain, for example, URL parameters* used to track the source of the traffic. If not provided, the default value* is `[/^utm_/, /^fbclid$/]`.**/ignoreURLParametersMatching?: Array<RegExp>;/*** When using Workbox's build tools to generate your service worker, you can* specify one or more runtime caching configurations. These are then* translated to {@link workbox-routing.registerRoute} calls using the match* and handler configuration you define.** For all of the options, see the {@link workbox-build.RuntimeCaching}* documentation. The example below shows a typical configuration, with two* runtime routes defined:** @example* runtimeCaching: [{*   urlPattern: ({url}) => url.origin === 'https://api.example.com',*   handler: 'NetworkFirst',*   options: {*     cacheName: 'api-cache',*   },* }, {*   urlPattern: ({request}) => request.destination === 'image',*   handler: 'StaleWhileRevalidate',*   options: {*     cacheName: 'images-cache',*     expiration: {*       maxEntries: 10,*     },*   },* }]*/runtimeCaching?: Array<RuntimeCaching>;/*** Whether to create a sourcemap for the generated service worker files.* @default true*/sourcemap?: boolean;
}

重点关注:

  • ignoreURLParametersMatching:默认无法缓存html后面带参数的页面,加上它忽略参数就可以缓存了
  • runtimeCaching: 运行时缓存,可以自定义配置各种类型的缓存,最后我们会详细介绍
  • sourcemap: 是否生成sourcemap,它记录了转换压缩后的代码所对应的转换前的源代码位置,方便定位问题
四:将上面的配置,应用到vite.config.ts/js文件
// vite.config.ts/js
import { VitePWA } from 'vite-plugin-pwa'
export default {plugins: [VitePWA({workbox:{globIgnores: ['static/js/**'],globPatterns: ["**/*.{js,css,html,ico,jpg,png,svg}"],ignoreURLParametersMatching: [/.*/],sourcemap:true,}})]
}
五:自定义配置缓存

随着项目越来越庞大或者需求越来越复杂,有时候我们需要,缓存某些特定的路径文件,或者请求类型,以及单独设置js或者html的缓存时间和个数,这个时候我们就需要用到runtimeCaching配置

export interface RuntimeCaching {/*** This determines how the runtime route will generate a response.* To use one of the built-in {@link workbox-strategies}, provide its name,* like `'NetworkFirst'`.* Alternatively, this can be a {@link workbox-core.RouteHandler} callback* function with custom response logic.*/handler: RouteHandler | StrategyName;/*** The HTTP method to match against. The default value of `'GET'` is normally* sufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or* another type of request.* @default "GET"*/method?: HTTPMethod;/*** This match criteria determines whether the configured handler will* generate a response for any requests that don't match one of the precached* URLs. If multiple `RuntimeCaching` routes are defined, then the first one* whose `urlPattern` matches will be the one that responds.** This value directly maps to the first parameter passed to* {@link workbox-routing.registerRoute}. It's recommended to use a* {@link workbox-core.RouteMatchCallback} function for greatest flexibility.*/urlPattern: RegExp | string | RouteMatchCallback;options?: {/*** Configuring this will add a* {@link workbox-cacheable-response.CacheableResponsePlugin} instance to* the {@link workbox-strategies} configured in `handler`.*/cacheableResponse?: CacheableResponseOptions;/*** If provided, this will set the `cacheName` property of the* {@link workbox-strategies} configured in `handler`.*/cacheName?: string | null;/*** Configuring this will add a* {@link workbox-expiration.ExpirationPlugin} instance to* the {@link workbox-strategies} configured in `handler`.*/expiration?: ExpirationPluginOptions;};
}

重点关注:

  • handler: 取缓存的策略,有五种

    type StrategyName = 'CacheFirst' | 'CacheOnly' | 'NetworkFirst' | 'NetworkOnly' | 'StaleWhileRevalidate';
    
    • CacheFirst:缓存优先
    • CacheOnly:仅使用缓存中的资源
    • NetworkFirst:网络优先
    • NetworkOnly:仅使用正常的网络请求
    • StaleWhileRevalidate:从缓存中读取资源的同时发送网络请求更新本地缓存
  • method: 默认是缓存get请求的资源,想缓存post的可以配置

  • urlPattern: 通过正则,字符或者函数形式匹配要缓存的资源类型

  • options自定义配置项

    • cacheableResponse: 缓存状态码正确的资源,比如200的
    • cacheName: 自定义缓存的类型名称
    • expiration: 设置缓存的时间,数量。超过数量就删除之前的

想解决我最开始抛出的,前后端域名相同,导致的下载或者导出失败问题,可以做如下配置:

// vite.config.ts/js
import { VitePWA } from 'vite-plugin-pwa'
export default {plugins: [VitePWA({workbox: {maximumFileSizeToCacheInBytes: 50000000,globPatterns: [],runtimeCaching: [{// 路径url中包含ai-synergy或者auth,handler设置成NetworkOnlyurlPattern: /.*\/(ai-synergy|auth).*/,handler: 'NetworkOnly',options: {cacheName: 'ai-synergy|auth',cacheableResponse: {statuses: [200]}}}]}})]
}

最后是更加完善的自定义配置方案:

VitePWA({workbox: {globPatterns: [],runtimeCaching: [mode !== 'production'? {urlPattern: ({ url }) => url.origin === 'https://xxx.list.com',handler: 'NetworkFirst',options: {cacheName: 'list',cacheableResponse: {statuses: [200]}}}: {urlPattern: ({ url }) => url.origin === 'https://xxx.detail.com',handler: 'NetworkFirst',options: {cacheName: 'detail',cacheableResponse: {statuses: [200]}}},{urlPattern: /.*\/(ai-synergy|auth).*/,handler: 'NetworkOnly',options: {cacheName: 'ai-synergy|auth',cacheableResponse: {statuses: [200]}}},{urlPattern: /\.(?:png|jpg|jpeg|svg)$/,handler: 'CacheFirst',options: {cacheName: 'images',expiration: {// 最多20个图maxEntries: 20}}},{urlPattern: /.*\.js.*/,handler: 'StaleWhileRevalidate',options: {cacheName: 'js',expiration: {maxEntries: 30, // 最多缓存30个,超过的按照LRU原则删除maxAgeSeconds: 30 * 24 * 60 * 60},cacheableResponse: {statuses: [200]}}},{urlPattern: /.*\.css.*/,handler: 'StaleWhileRevalidate',options: {cacheName: 'css',expiration: {maxEntries: 20,maxAgeSeconds: 30 * 24 * 60 * 60},cacheableResponse: {statuses: [200]}}},{urlPattern: /.*\.html.*/,handler: 'StaleWhileRevalidate',options: {cacheName: 'html',expiration: {maxEntries: 20,maxAgeSeconds: 30 * 24 * 60 * 60},cacheableResponse: {statuses: [200]}}}]},})

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_306526.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

npm更换成淘宝镜像源及cnpm使用

1.需求由来 由于node安装插件是从国外服务器下载&#xff0c;受网络影响大&#xff0c;速度慢且可能出现异常。所以如果npm的服务器在中国就好了&#xff0c;所以我们乐于分享的淘宝团队&#xff08;阿里巴巴旗下业务阿里云&#xff09;干了这事。来自官网&#xff1a;“这是一…

AnsiConsole-能够编写 ANSI 转义序列的控制台

Spectre.Console 是一款 .NET 库&#xff0c;提供了一种简单但强大的方式来创建美观和交互式的控制台应用程序。它允许开发人员轻松构建具有颜色、表格、进度条等功能的富命令行界面 (CLI)。 功能 Spectre.Console 的一些显着功能包括&#xff1a; 颜色&#xff1a;Spectre.C…

单片机GD32F303RCT6 (Macos环境)开发 (二十八)—— 蓝牙透传模块HC-08 Android App开发

蓝牙透传模块HC-08 Android App开发 1、App整体开发思路 a、首先要申请权限&#xff0c;采用动态申请的方式&#xff0c;用户点击确认后方可操作蓝牙。 b、搜索蓝牙&#xff0c;之前的版本用startLeScan函数搜索蓝牙&#xff0c;虽然高版本中依然可用&#xff0c;但是google已…

4.Ansible Inventory介绍及实战 - A list or group of lists nodes

什么是inventory&#xff1f; 官方解释&#xff1a;Ansible automates tasks on managed nodes or “hosts” in your infrastructure, using a list or group of lists known as inventory. Ansible可以同时与您基础设施中的一个或多个系统协同工作&#xff61;为了与多台服务…

接口测试的请求和响应

接口测试的请求和响应 在软件开发中&#xff0c;接口测试是必不可少的一环节。接口测试主要涉及到测试请求和响应的过程。请求是指客户端向服务器发送的一些指令或数据&#xff0c;而响应则是服务器对这些请求做出的回应。 请求通常包括请求方法、请求头以及请求体。请求方法有…

【什么是iMessage苹果推?】什么是苹果推信?什么是苹果推?

挑选得当的IM推送平台&#xff1a;选择合用于PC真个IM推送平台 开辟或集成API&#xff1a;依照所选平台的开发文档&#xff0c;利用响应的编程语言&#xff08;如Python、Java等&#xff09;开发或集成API&#xff0c;以便与平台举行交互和节制。API可用于建立、办理和发送消息…

【HarmonyOS】【FAQ】HarmonyOS应用开发相关问题解答(二)

【写在前面】 之前和大家分享过一下HarmonyOS应用开发相关问题&#xff0c;今天继续和大家分享&#xff01; 【前提简介】 本文档主要总结HarmonyOS开发过程中可能遇到的一些问题解答&#xff0c;主要围绕HarmonyOS展开&#xff0c;包括但不限于不同API版本HarmonyOS开发、UI…

单体项目偶遇并发漏洞!短短一夜时间竟让老板蒸发197.83元

事先声明&#xff1a;以下故事基于真实事件而改编&#xff0c;如有雷同&#xff0c;纯属巧合~ 眼下这位正襟危坐的男子&#xff0c;名为小竹&#xff0c;他正是本次事件的主人公&#xff0c;也即将成为熊猫集团的被告&#xff0c;嗯&#xff1f;这究竟怎么一回事&#xff1f;欲…

Linux网络编程—Day10

Linux服务器程序规范 Linux服务器程序一般以后台进程形式运行。后台进程又称守护进程。它没有控制终端&#xff0c;因而也不会意外接收到用户输入。 守护进程的父进程通常是init进程&#xff08;PID为1的进程&#xff09;&#xff1b;Linux服务器程序通常有一套日志系统&#…

设备快线客户端软件V1.0用户手册

1.前言欢迎使用设备快线客户端软件产品。设备快线客户端软件简称DYClient,DYClient客户端是东用科技有限公司推出的一款用于远程维护的控制软件&#xff0c;主要为客户远程访问现场终端设备提供便捷的接入服务&#xff0c;并且通过DYClient客户端软件用户可以非常方便快捷的访问…

基于RetinaNet和TensorFlow Object Detection API实现目标检测(附源码)

文章目录 一、RetinaNet原理二、RetinaNet实现1. tf.train.CheckPoint简介2. RetinaNet的TensorFlow源码 一、RetinaNet原理 待补充 二、RetinaNet实现 1. tf.train.CheckPoint简介 待补充 2. RetinaNet的TensorFlow源码 Step 1&#xff1a;安装Tensorflow 2 Object Detect…

云原生之深入解析Docker容器退出码的含义和产生原因

一、前言 为什么我的容器没有运行?回答这个问题之前,需要知道 Docker 容器为什么退出?退出码会提示容器停止运行的情况?本文列出最常见的退出码,来回答两个重要问题:这些退出码是什么意思?导致该退出码的动作是什么?exit code:代表一个进程的返回码,通过系统调用 exi…

chatgpt赋能python:Python修改密码:一种安全可靠、快速高效的方式

Python 修改密码&#xff1a;一种安全可靠、快速高效的方式 在数字化时代&#xff0c;越来越多的信息被存储在计算机系统中&#xff0c;因此密码的保护变得尤为重要。人们需要保证他们的密码是安全可靠的&#xff0c;并定期更换密码。Python作为一种强大而且通用的编程语言&am…

iOS-最全的App上架教程

App上架教程 在上架App之前想要进行真机测试的同学&#xff0c;请查看《iOS- 最全的真机测试教程》&#xff0c;里面包含如何让多台电脑同时上架App和真机调试。 P12文件的使用详解 注意&#xff1a; 同样可以在Build Setting 的sign中设置证书&#xff0c;但是有点麻烦&…

生态伙伴 | 携手深圳科创学院,持续推动项目落地与成长

01 大赛介绍 中国硬件创新创客大赛始于2015年&#xff0c;由深圳华秋电子有限公司主办&#xff0c;至今已经成功举办八届&#xff0c;赛事范围覆盖华南、华东、华北三大地区&#xff0c;超10个省市区域。 大赛影响了超过45万工程师群体&#xff0c;吸引了35000多名硬创先锋报…

Linux文件系统、磁盘I/O是怎么工作的?

同CPU、内存一样&#xff0c;文件系统和磁盘I/O&#xff0c;也是Linux操作系统最核心的功能。磁盘为系统提供了最基本的持久化存储。文件系统则在磁盘基础上&#xff0c;提供了一个用来管理文件的树状结构。 目录&#xff1a; 一. 文件系统 1. 索引节点和目录项 2. 虚拟文件系…

抖音短视频APP的益与害都存在,今日详解其利弊

抖音是一款音乐创意短视频社交软件&#xff0c;是一个专注年轻人的15秒音乐短视频社区。这两年抖音太火了&#xff0c;不若与众身边的朋友百分之八十的朋友手机上都有这个软件&#xff0c;即使不拍也会抱着手机刷到停不下来。 首先&#xff0c;抖音其实给人们带来了许多乐趣和娱…

兼容性测试点和注意项,建议收藏

一&#xff1a;兼容性测试的概念&#xff1a;就是验证开发出来的程序在特定的运行环境中与特定的软件、硬件或数据相组合是否能正常运行、有无异常的测试过程。 二&#xff1a;兼容性测试的分类&#xff1a; &#xff08;1&#xff09;浏览器兼容性测试 指的是在浏览器上检查…

【CCF- CSP 202104-2 邻域均值 二维数组前缀和满分题解】

代码思路&#xff1a; 本题如果直接用暴力求解的话只能得70分。 运用到了二维数组的前缀和&#xff0c;难点是如何求出二维数组的前缀和并计算出领域所有元素的和。 注意计算平均数的时候要保证精度相同&#xff0c;所有都要化为double型&#xff0c;否则会出错。 首先&…

基于SpringBoot+Vue的闲一品交易平台设计与实现

博主介绍&#xff1a; 大家好&#xff0c;我是一名在Java圈混迹十余年的程序员&#xff0c;精通Java编程语言&#xff0c;同时也熟练掌握微信小程序、Python和Android等技术&#xff0c;能够为大家提供全方位的技术支持和交流。 我擅长在JavaWeb、SSH、SSM、SpringBoot等框架下…