vite-plugin-pwa配置详解

news/2024/9/18 8:07:32/

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.ppmy.cn/news/87762.html

相关文章

Worker及XMLHttpRequest简单使用说明

Worker 一、作用及使用场景 在Web应用程序中创建多线程环境&#xff0c;可以运行独立于主线程的脚本&#xff0c;从而提高Web应用的性能和响应速度。 Worker.js主要应用场景包括&#xff1a; 数据处理&#xff1a;在数据量较大的情况下&#xff0c;使用Worker可以将数据分成…

抖音seo源码开发,开源技术保姆式搭建

抖音seo源码优化逻辑 抖音SEO是通过一系列的技术手段和优化策略来提升视频内容在抖音平台内的曝光率和排名。其中主要包括以下几个方面&#xff1a; 1.关键词优化。通过对视频的标题、描述等元素的关键词进行优化&#xff0c;提高相关性和匹配度&#xff0c;让用户更容易搜索到…

Java split()方法中的特殊符号

一、split是什么&#xff1f; 在Java中&#xff0c;split()方法用于分隔字符串&#xff0c;可以根据匹配给定的正则表达式来拆分字符串。split()方法可以将一个字符串分割为子字符串&#xff0c;然后将结果作为字符串数组返回&#xff1b;语法如下&#xff0c;其中参数regex指…

【SpringCloud】三、Nacos服务注册+配置管理+集群搭建

文章目录 一、认识Nacos1、安装2、服务注册和发现3、服务分级存储模型4、负载均衡策略--NacosRule5、服务实例的权重设置5、环境隔离namespace6、Eureka和Nacos的区别 二、Nacos配置管理1、统一配置管理2、微服务配置拉取3、配置热更新4、多环境配置共享 三、Nacos集群搭建1、初…

【2023年电工杯数学建模竞赛】选题分析+A题B题完整思路+代码分享

思路和代码会第一时间分享出来&#xff0c;可以先关注博主 1.竞赛介绍 2.本次大赛选题分析 首先大家要清楚获奖只和比例有关&#xff0c;和具体题目关系不大&#xff0c;不会出现选难题就比简单题获奖率高很多的情况出现&#xff0c;这是一个选拔性质的比赛是按照比例来的 2…

如何声明和初始化变量?

在Java中&#xff0c;声明和初始化变量可以通过以下方式进行&#xff1a; 声明变量并赋初值&#xff1a; javaCopy code dataType variableName initialValue; 其中&#xff0c;dataType是变量的数据类型&#xff0c;variableName是变量名&#xff0c;initialValue是变量的初…

操作系统第四章——文件管理(下)

竹本无心&#xff0c;却节外生枝&#xff0c;藕却有孔&#xff0c;但出淤泥而不染&#xff0c;人生如梦&#xff0c;却却不随人愿&#xff0c;万般皆是命&#xff0c;半点不由人 文章目录 4.1.5 逻辑结构VS物理结构4.1.6 文件的基本操作知识总览创建文件删除文件打开文件关闭文…

自古以来,反射也是兵家必争之地

成文耗时1小时&#xff0c;阅读5min&#xff0c;有用指数5颗星。 这几天收到一个战术性需求&#xff0c;将一大坨字段序列化为特定格式的字符串。 大概是下表&#xff1a; 序号字段名描述是否必填0logVersion日志版本是1productName产品是2serviceName服务是.........25extend3…

burpsuite导入网站的客户端证书

0x01 背景 个别网站需要导入客户端的XX.P12证书&#xff0c;如果没有导入直接访问网站&#xff0c;浏览器会提示&#xff1a;400 Bad Request , 出现&#xff1a;No required SSL certificate was sent等提示&#xff0c;如下图 此时需要在burpsuite中导入证书 0x02 网站客户…

基于SpringBoot+Uniapp的球队周边微信小程序

✌全网粉丝20W,csdn特邀作者、博客专家、CSDN新星计划导师、java领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取项目下载方式&#x1f345; 一、项目背景介绍&#xff1a; 随着微信小程序的兴起…

企业级实战 Spring Boot + K8S 中的滚动发布、优雅停机、弹性伸缩、应用监控、配置分离

下面为大家介绍我司生产环境使用了3年的基于K8S的dev ops 配置实现 K8s SpringCloud实现零宕机发版&#xff0c;优雅重启&#xff1a;健康检查滚动更新优雅停机弹性伸缩Prometheus监控配置分离&#xff08;镜像复用&#xff09; 汇总配置 业务层面 项目依赖 pom.xml 使用 s…

版图设计IC617 virtuoso启动以及smic18mmrf加载库

一. 启动virtuoso 1.1 创建一个目录用于库管理 mkdir pro3 1.2 拷贝.bashrc到工程目录下&#xff0c;.bashrc存在~目录下&#xff0c;是一个隐藏文件&#xff0c;需要用ls -la查看 1.3 执行.bashrc文件 1.4 启动 virtuoso & 1.5 检查库中是否包含系统基本库&#xff0c;如…

python 生成器

生成器 Python生成器是一种特殊的函数,它可以在需要时生成一系列值,而不是一次性生成所有值。生成器使用yield关键字来暂停函数的执行,并返回一个值。当函数再次被调用时,它将从yield语句停止的地方继续执行。所以生成器非常适合处理大量数据或无限序列。 生成器…

【TI毫米波雷达笔记】IWR6843AOPEVM-G的DCA1000EVM模式配置及避坑

【TI毫米波雷达笔记】IWR6843AOPEVM-G的DCA1000EVM模式配置及避坑 IWR6843AOPEVM-G版本可以直接与DCA1000EVM连接 进行数据获取 不需要连接MMWAVEICBOOST版 直接使用 DCA1000mmWave Studio 软件进行数据采集 在官方手册中 User’s Guide 60GHz 毫米波传感器EVM 有相关模式的开…

滤镜美颜sdk的实现方式和工作流程:从技术层面了解美颜算法

众所周知&#xff0c;实现美颜功能的核心技术之一就是滤镜美颜sdk。在本文中&#xff0c;我们将从技术层面来探讨滤镜美颜sdk的实现方式和工作流程&#xff0c;帮助读者更深入了解美颜算法。 一、美颜算法的基本原理 美颜算法的基本原理是通过图像处理技术&#xff0c;对人物…

MyBatisPlus快速入门(二)MyBatisPlus快速入门体验

一、初始化数据库&#xff08;基于 HeidiSQL&#xff09;1.1 创建数据库1.2创建数据表1.3 初始化数据 二、初始化项目&#xff08;基于Spring Boot&#xff09;2.1 创建项目2.2 新增依赖2.3 数据库配置2.4 配置 MyBatis Plus2.5 创建实体类2.6 创建Mapper层接口2.7 创建Server层…

AI技术将手语翻译带入新阶段

对于无声者来说&#xff0c;手语可能就是对外交流的唯一方法&#xff0c;但是随着AI技术的进步&#xff0c;可能会让无声者有更多的选择与和外界进行交流。 近日在巴塞罗那超级计算中心(BSC)和加泰罗尼亚理工大学(UPC)携手合作取得了重大突破&#xff0c;他们成功开发出一项全…

微信小程序 基础模板引入sass的两种方法

推荐使用第二种方法 一、VSCode扩展引入&#xff08;旧&#xff09; 1.vscode搜索扩展 Easy Sass安装 2.微信开发者工具导入vscode安装的所有扩展 3.修改sass扩展配置 打开扩展目录 找到刚导入的sass扩展 打开package.json文件 改成这样 保存 4.重新打开此项目 配置完事 5.使…

基于 typescript 装饰器实现 express 路由

目录 使用装饰器分析装饰器实现自动加载使用 使用 我们先来看看原生的使用方式和使用装饰器实现的使用方式&#xff0c;这样子可以让我们更加直观的感受到区别 原生的使用方式 import { Router } from "express";const router Router();router.use((req, res, ne…

量子OFFICE:TrueType/FreeType/OpenType的概念

FreeType各项功能都有&#xff0c;为什么要改进呢&#xff1f;为了做得跟WORD一样啊。 结合自己以前在研究的时候&#xff0c;看到的资料&#xff0c;介绍几个概念&#xff1a; TrueType是一种矢量字体规范 如果是位图字体&#xff0c;不同字号就要有不同的位置&#xff0c;工…