https://github.com/qzruncode/sophic-sw-webpack-plugin
https://github.com/qzruncode/sophic-sw-webpack-plugin
Last synced: 11 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/qzruncode/sophic-sw-webpack-plugin
- Owner: qzruncode
- Created: 2023-01-08T06:52:22.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-04-27T09:01:28.000Z (about 3 years ago)
- Last Synced: 2025-07-31T11:54:05.438Z (12 months ago)
- Language: JavaScript
- Size: 8.79 KB
- Stars: 1
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
[](https://www.npmjs.com/package/sophic-sw-webpack-plugin)
[](https://www.npmjs.com/package/sophic-sw-webpack-plugin)
## sophic-sw-webpack-plugin
1. 此插件为[sophic](https://www.npmjs.com/package/sophic)而设计,用来生成sw文件,从而使用sophic中的sw缓存模式,存储微应用的静态资源
2. 此插件最好在[dark-tunnel](https://www.npmjs.com/package/dark-tunnel)脚手架中使用
3. 提供配置项expirationHour用来设置缓存时效,不建议过长
### 安装
```
npm install -D sophic-sw-webpack-plugin
```
### 使用
```
在使用dark-tunnel创建的项目根目录新建 darkTunnel.config.js
const cachewebWebpackPlugin = require('sophic-sw-webpack-plugin');
module.exports = [
new cachewebWebpackPlugin({
expirationHour: 2
}),
];
在使用dark-tunnel编译项目后,会在build目录下生成sw.js文件
```
### 注册
```
在使用dark-tunnel创建的项目根目录新建 static/registerSW.js
function registerSW() {
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/sw.js", { scope: '/' })
.then((registration) => {
let serviceWorker;
if (registration.installing) {
serviceWorker = registration.installing;
} else if (registration.waiting) {
serviceWorker = registration.waiting;
} else if (registration.active) {
serviceWorker = registration.active;
}
if (serviceWorker) {
serviceWorker.addEventListener("statechange", function (e) {
console.log("sw的状态改变:" + e.target.state);
});
}
});
navigator.serviceWorker.onmessage = (e) => {
console.log("onmessage", e);
const { data } = e;
if (data.type === "FetchError") {
// 请求失败;
} else if (data.type === "NetWorkError") {
// 断网
} else if (data.type === "RefreshClient") {
// 刷新页面,有新版本的sw安装
location.reload();
}
};
} else {
console.log("sw不支持");
}
}
```