vue-sw-updater 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md ADDED
@@ -0,0 +1,36 @@
1
+ # vue2-sw-update
2
+
3
+ #### Description
4
+ 针对vue2的 service-worker更新提示
5
+
6
+ #### Software Architecture
7
+ Software architecture description
8
+
9
+ #### Installation
10
+
11
+ 1. xxxx
12
+ 2. xxxx
13
+ 3. xxxx
14
+
15
+ #### Instructions
16
+
17
+ 1. xxxx
18
+ 2. xxxx
19
+ 3. xxxx
20
+
21
+ #### Contribution
22
+
23
+ 1. Fork the repository
24
+ 2. Create Feat_xxx branch
25
+ 3. Commit your code
26
+ 4. Create Pull Request
27
+
28
+
29
+ #### Gitee Feature
30
+
31
+ 1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
32
+ 2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
33
+ 3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
34
+ 4. The most valuable open source project [GVP](https://gitee.com/gvp)
35
+ 5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
36
+ 6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
package/README.md ADDED
@@ -0,0 +1,106 @@
1
+ # Vue Service Worker Updater
2
+
3
+ 一个基于 Vue 2 和 Ant Design Vue 的项目更新通知与缓存清理方案。
4
+
5
+ ## 功能特性
6
+
7
+ * **自动检测更新**: 基于 Service Worker API,自动感知应用版本更新。
8
+ * **零侵入集成**: Service Worker 逻辑由本库维护,无需手动编写复杂的 SW 代码。
9
+ * **多环境隔离**: 支持 `appName` 和 `env` 参数,生成独立的缓存空间,避免多应用或多环境缓存冲突。
10
+ * **全局提示**: 使用 Ant Design Vue Modal 全局弹窗提示用户,样式醒目(警告图标+加粗文字)。
11
+ * **强制刷新**: 用户点击“立即更新”后,自动清理当前应用缓存并重载页面,确保加载最新资源。
12
+ * **环境检测**: 自动检测浏览器版本,如果不支持 Service Worker 或版本过低,会显示阻断性提示。
13
+
14
+ ## 安装
15
+
16
+ ```bash
17
+ npm install vue-sw-updater --save
18
+ # 确保项目中已安装 ant-design-vue 和 vue
19
+ npm install ant-design-vue vue --save
20
+ ```
21
+
22
+ ## 快速使用
23
+
24
+ ### 1. 引入插件
25
+
26
+ 在你的 `main.js` 或入口文件中:
27
+
28
+ ```javascript
29
+ import Vue from 'vue';
30
+ import VueSWUpdater from 'vue-sw-updater';
31
+ import 'ant-design-vue/dist/antd.css';
32
+
33
+ // 从你的配置或环境变量中获取信息
34
+ const version = process.env.VUE_APP_VERSION || '1.0.0';
35
+ const appName = process.env.VUE_APP_NAME || 'my-app';
36
+ const env = process.env.NODE_ENV || 'production';
37
+
38
+ Vue.use(VueSWUpdater, {
39
+ // 必须:应用版本号
40
+ version: version,
41
+
42
+ // 必须:应用名称(用于隔离缓存)
43
+ appName: appName,
44
+
45
+ // 必须:部署环境(用于隔离缓存,如 production, staging)
46
+ env: env,
47
+
48
+ // 可选:Service Worker 文件路径,默认为 /service-worker.js
49
+ swUrl: '/service-worker.js',
50
+
51
+ // 可选:调试模式
52
+ debug: false
53
+ });
54
+ ```
55
+
56
+ ### 2. 部署 Service Worker 文件
57
+
58
+ 本库提供了一个通用的 `service-worker.js`,你需要将其包含在你的项目根目录(`public` 目录)中。
59
+
60
+ **方式 A:构建时复制 (推荐)**
61
+
62
+ 如果你使用 Webpack (Vue CLI),可以使用 `copy-webpack-plugin` 将本库的 SW 文件复制到你的构建目录。
63
+
64
+ ```javascript
65
+ // vue.config.js
66
+ const CopyWebpackPlugin = require('copy-webpack-plugin');
67
+ const path = require('path');
68
+
69
+ module.exports = {
70
+ configureWebpack: {
71
+ plugins: [
72
+ new CopyWebpackPlugin({
73
+ patterns: [
74
+ {
75
+ from: path.resolve(__dirname, 'node_modules/vue-sw-updater/dist/service-worker.js'),
76
+ to: 'service-worker.js' // 输出到 dist 根目录
77
+ }
78
+ ]
79
+ })
80
+ ]
81
+ }
82
+ }
83
+ ```
84
+
85
+ ## 更新机制说明
86
+
87
+ 1. 当传入的 `version` 发生变化时,插件会注册带有新参数的 Service Worker(例如 `/service-worker.js?v=1.0.1&app=my-app&env=production`)。
88
+ 2. 浏览器检测到 URL 变化,重新下载并安装 Service Worker。
89
+ 3. 新 SW 初始化时,会根据 `appName` + `env` + `version` 生成全新的 Cache Key。
90
+ 4. 当检测到新版本等待激活(Waiting)时,弹出**警告样式**的更新提示框。
91
+ 5. 用户点击“立即更新”:
92
+ * 发送 `SKIP_WAITING` 消息给 SW。
93
+ * SW 收到消息后,**立即清理当前应用环境下的旧缓存**。
94
+ * SW 执行 `self.skipWaiting()` 激活新版本。
95
+ * 页面监听到 `controllerchange` 事件,执行 `window.location.reload()` 刷新页面。
96
+
97
+ ## 浏览器支持
98
+
99
+ 插件会自动检测以下浏览器版本要求:
100
+
101
+ * Chrome: 45+
102
+ * Firefox: 44+
103
+ * Safari: 11+
104
+ * Edge: 17+
105
+
106
+ 如果用户浏览器版本低于上述要求,将自动显示全屏提示,建议用户升级。
package/dist/demo.html ADDED
@@ -0,0 +1 @@
1
+ <!doctype html><meta charset="utf-8"><title>vue-sw-updater demo</title><script src="./vue-sw-updater.umd.js"></script><script>console.log(vue-sw-updater)</script>
@@ -0,0 +1,127 @@
1
+ /* eslint-disable */
2
+ // 此文件由 vue-sw-updater 库维护
3
+ // 集成时请确保此文件被复制到构建输出目录(如 dist/service-worker.js)
4
+ // 并确保通过 http://your-domain/service-worker.js 可以访问
5
+
6
+ // 获取参数(从注册 URL 参数中获取)
7
+ const params = new URLSearchParams(self.location.search);
8
+ const VERSION = params.get('v') || '1.0.0';
9
+ const APP_NAME = params.get('app') || 'vue-app';
10
+ const ENV = params.get('env') || 'production';
11
+
12
+ // 生成 Cache Key: appName-env-version
13
+ const CACHE_PREFIX = `${APP_NAME}-${ENV}`;
14
+ const CACHE_NAME = `${CACHE_PREFIX}-${VERSION}`;
15
+
16
+ // 需要忽略缓存的路径(可选,可以通过参数扩展)
17
+ const BLACKLIST = [
18
+ '/service-worker.js',
19
+ '/api/' // 假设 API 请求不缓存
20
+ ];
21
+
22
+ console.log(`[VueSWUpdater] Service Worker 初始化. App: ${APP_NAME}, Env: ${ENV}, Version: ${VERSION}, Cache: ${CACHE_NAME}`);
23
+
24
+ self.addEventListener('install', (event) => {
25
+ console.log('[VueSWUpdater] Installing...');
26
+ event.waitUntil(
27
+ caches.open(CACHE_NAME).then((cache) => {
28
+ // 仅缓存核心入口文件,其他资源依赖运行时缓存
29
+ return cache.addAll([
30
+ './',
31
+ './index.html'
32
+ ]).catch(err => {
33
+ console.warn('[VueSWUpdater] Pre-caching failed:', err);
34
+ });
35
+ })
36
+ );
37
+ // 注意:这里不调用 skipWaiting(),等待用户点击更新确认后,由主线程发送消息触发
38
+ });
39
+
40
+ self.addEventListener('activate', (event) => {
41
+ console.log('[VueSWUpdater] Activating...');
42
+ event.waitUntil(
43
+ caches.keys().then((keyList) => {
44
+ return Promise.all(keyList.map((key) => {
45
+ // 清理旧版本缓存 (只清理本插件前缀的缓存)
46
+ // 逻辑:如果是同一个 App 和 Env,但是版本不同,则清理
47
+ if (key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME) {
48
+ console.log('[VueSWUpdater] Removing old cache:', key);
49
+ return caches.delete(key);
50
+ }
51
+ }));
52
+ })
53
+ );
54
+ return self.clients.claim();
55
+ });
56
+
57
+ // 监听 skipWaiting 消息(由 UI 组件触发)
58
+ self.addEventListener('message', (event) => {
59
+ if (event.data && event.data.type === 'SKIP_WAITING') {
60
+ console.log('[VueSWUpdater] Skip Waiting received');
61
+
62
+ // 强制清理所有缓存(不仅仅是旧版本,确保彻底)
63
+ // 注意:这里只清理当前 APP_NAME 和 ENV 下的缓存,防止误删其他应用缓存
64
+ // 但根据需求“清理当前应用的缓存”,我们可以在 skipWaiting 前做一次彻底清理
65
+ caches.keys().then(keys => {
66
+ keys.forEach(key => {
67
+ if (key.startsWith(CACHE_PREFIX)) {
68
+ console.log('[VueSWUpdater] Force clearing cache before update:', key);
69
+ caches.delete(key);
70
+ }
71
+ });
72
+ });
73
+
74
+ self.skipWaiting();
75
+ }
76
+ });
77
+
78
+ self.addEventListener('fetch', (event) => {
79
+ // 忽略非 GET 请求
80
+ if (event.request.method !== 'GET') return;
81
+
82
+ // 忽略黑名单路径
83
+ const url = new URL(event.request.url);
84
+ if (BLACKLIST.some(path => url.pathname.startsWith(path))) return;
85
+
86
+ // HTML 页面:网络优先,失败回退到缓存 (Network First)
87
+ if (event.request.mode === 'navigate' || event.request.headers.get('accept').includes('text/html')) {
88
+ event.respondWith(
89
+ fetch(event.request)
90
+ .then(response => {
91
+ // 网络请求成功,更新缓存
92
+ const responseClone = response.clone();
93
+ caches.open(CACHE_NAME).then(cache => {
94
+ cache.put(event.request, responseClone);
95
+ });
96
+ return response;
97
+ })
98
+ .catch(() => {
99
+ // 网络失败,使用缓存
100
+ return caches.match(event.request);
101
+ })
102
+ );
103
+ return;
104
+ }
105
+
106
+ // 静态资源:缓存优先,同时更新缓存 (Stale While Revalidate)
107
+ // 或者简单的 Cache First,这里为了稳健使用 Cache First + Network Fallback
108
+ event.respondWith(
109
+ caches.match(event.request).then((response) => {
110
+ if (response) {
111
+ return response;
112
+ }
113
+ return fetch(event.request).then(networkResponse => {
114
+ // 动态缓存请求成功的资源
115
+ if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
116
+ return networkResponse;
117
+ }
118
+ const responseToCache = networkResponse.clone();
119
+ caches.open(CACHE_NAME).then(cache => {
120
+ // 避免缓存过大文件或不必要文件,这里可以加过滤逻辑
121
+ cache.put(event.request, responseToCache);
122
+ });
123
+ return networkResponse;
124
+ });
125
+ })
126
+ );
127
+ });