vue-sw-updater
v0.0.1-beta.2
Published
A project update notification and cache cleanup solution based on Vue 2 and Ant Design Vue. Supports dual mechanisms of Service Worker automatic update and HTTP polling update detection, ensuring reliable operation in both HTTPS and HTTP environments.
Readme
Vue Service Worker Updater
A project update notification and cache cleanup solution based on Vue 2 and Ant Design Vue. Supports dual mechanisms of Service Worker automatic update and HTTP polling update detection, ensuring reliable operation in both HTTPS and HTTP environments.
Features
- Dual Update Detection Mode:
- Service Worker Mode: In HTTPS environments, uses SW to automatically detect application updates, supporting offline caching and incremental updates.
- HTTP Polling Mode: In HTTP environments or browsers that do not support SW, automatically downgrades to ETag / Last-Modified polling detection.
- Zero-Intrusion Integration: Core logic is encapsulated within the library, no need to manually write complex SW or polling code.
- Multi-Environment Isolation: Supports
appNameandenvparameters to generate independent cache spaces, avoiding cache conflicts across multiple apps or environments. - Global Notification: Uses Ant Design Vue Modal for global pop-up prompts to users, with a striking style (warning icon + bold text).
- Force Refresh: After the user clicks "Update Now", automatically clears the current application cache and reloads the page to ensure the latest resources are loaded.
- Environment Adaptation: Automatically detects environment security (HTTPS/localhost). If the environment is insecure and polling parameters are configured, it automatically switches to polling mode; otherwise, it shows an environment not supported prompt.
Installation
npm install vue-sw-updater --save
# Ensure ant-design-vue and vue are installed in your project
npm install ant-design-vue vue --saveQuick Start
1. Import Plugin
In your main.js or entry file:
import Vue from 'vue';
import VueSWUpdater from 'vue-sw-updater';
import 'ant-design-vue/dist/antd.css';
// Get information from your configuration or environment variables
const version = process.env.VUE_APP_VERSION || '1.0.0';
const appName = process.env.VUE_APP_NAME || 'my-app';
const env = process.env.NODE_ENV || 'production';
Vue.use(VueSWUpdater, {
// [Optional] Update detection mode: 'auto' | 'sw' | 'poll'
// 'auto': (Default) Prioritize Service Worker, automatically downgrade to Polling mode if not supported
// 'sw': Use Service Worker only
// 'poll': Force use of HTTP Polling mode
type: 'auto',
// [Conditionally Required] App Version (Required only in auto/sw mode)
version: version,
// [Conditionally Required] App Name (Required only in auto/sw mode, used for SW cache isolation)
appName: appName,
// [Required] Deployment Environment (Required in auto/sw/poll modes)
env: env,
// [Optional] Service Worker file path, defaults to /service-worker.js
swUrl: '/service-worker.js',
// [Optional] Polling interval (minutes).
// If set > 0, polling mode will be enabled when SW is unavailable (e.g., HTTP environment).
// Recommended to set to 10 or 30.
pollingInterval: 10,
// [Optional] Target URL for update detection (Polling mode only)
// Defaults to root path '/', which checks the Header changes of the website root directory (usually index.html), preventing route parameter interference
checkUrl: '/',
// [Optional] Debug mode, outputs more logs to the console when enabled
debug: false
});2. Build Configuration (For Different Modes)
A. Prepare Service Worker (Recommended for HTTPS Mode)
This library provides a generic service-worker.js, which you need to include in your project root directory (public directory).
Webpack / Vue CLI Configuration:
// vue.config.js
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');
module.exports = {
configureWebpack: {
plugins: [
// Webpack 5+ / copy-webpack-plugin 6+ syntax:
new CopyWebpackPlugin({
patterns: [
{
from: path.resolve(__dirname, 'node_modules/vue-sw-updater/dist/service-worker.js'),
to: 'service-worker.js' // Output to dist root directory
}
]
})
// For Webpack 4 / copy-webpack-plugin < 6 syntax:
// new CopyWebpackPlugin([
// {
// from: path.resolve(__dirname, 'node_modules/vue-sw-updater/dist/service-worker.js'),
// to: 'service-worker.js'
// }
// ])
]
}
}B. HTTP Polling Mode Configuration
No extra files needed. The plugin will automatically poll the HTTP response headers of the website root path '/' (or specified checkUrl):
- ETag: Resource unique identifier
- Last-Modified: Resource last modified time
Note: Please ensure your Web Server (Nginx/Apache/IIS) is configured to return these Headers. For SPA application entry files (index.html), they are usually returned by default.
Operating Mechanism
1. Automatic Mode Selection (Default)
The plugin executes the following checks during initialization:
Check Service Worker Support:
- If HTTPS or localhost, and browser supports SW -> Enable SW Mode.
- If HTTP (non-localhost) or browser does not support SW -> Automatically downgrade to HTTP Polling Mode.
Fallback Behavior:
- If downgraded to polling mode and user hasn't set
pollingInterval, the plugin will automatically enable a default polling interval of 30 minutes.
- If downgraded to polling mode and user hasn't set
2. Forced Mode
You can force a specific mode via the type parameter:
type: 'poll': Ignore browser environment, force use of HTTP Polling Mode.type: 'sw': Attempt to use Service Worker. If the environment does not support it, current logic will also attempt to downgrade to ensure update availability.
SW Mode Workflow
- Plugin registers
service-worker.js?v=1.0.0&app=my-app.... - Browser detects URL change, downloads new SW.
- New SW installs and waits for activation.
- Plugin detects
waitingstate, pops up update prompt. - User clicks Update -> Clears cache -> Force refresh.
HTTP Polling Mode Workflow
- Plugin starts timer (e.g., every 10 minutes).
- Periodically sends
HEADrequest to detect target URL (default website root path). - Compares
ETagorLast-Modifiedin response headers with those at page load. - If Header change is detected, considers a new version is released, pops up update prompt.
- User clicks Update -> Force refresh (
window.location.reload(true)).
Browser Support
The plugin automatically handles compatibility, minimum requirements:
- Edge: 17+
- Chrome: 45+
- Firefox: 44+
- Safari: 11.1+
If the browser version is too low, a blocking prompt will be displayed regardless of the mode.
