如何解决Angular 如何在部署更新后刷新站点?
我使用的是 angular 10 + pwa ,所以一切都在缓存。服务器与 pm2 配合使用。
问题是我经常更新网站,每隔几天,有时更新后,用户仍然会在客户端看到旧视图,导致出现错误。
- 我的第一种方法是使用角度散列 - main.js -> main.864868684684.js ,但这对我来说并不真正有效,因为我无法告诉 pm2 每次加载不同的文件。
- 然后我在运行网站的快速服务器中禁用了缓存,但随后所有缓存都被禁用,所以这也很糟糕。
我正在寻找一种最佳方法,让我的用户始终可以看到我网站的最新版本 + 缓存可以正常工作。
如何实现?
解决方法
首先在你的 ngsw-config.json 中添加一个 version 标签:
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json","index": "/index.html","version": 327,/* Increment this on each publish */
"assetGroups": [
{
"name": "app","installMode": "prefetch","resources": {
"files": [
"/favicon.ico","/index.html","/*.css","/*.js","/manifest.webmanifest"
]
}
},{
"name": "assets","installMode": "lazy","updateMode": "prefetch","resources": {
"files": [
"/assets/**","/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
]
}
}
],"dataGroups": [
{
"name": "web","urls": [ /* Specify the api-calls/view that should be cached */
"/web/**","!/web/Account/**","!/web/v1/Account/**","!/web/v2/Account/**","!/api/**"
],"cacheConfig": {
"maxSize": 20,"maxAge": "1d","strategy": "freshness"
}
},{
"name": "amp","urls": [
"/amp/**"
],{
"name": "account","urls": [
"/web/Account/**","/web/v1/Account/**","/web/v2/Account/**"
],"cacheConfig": {
"maxSize": 0,"maxAge": "0u",{
"name": "external-callback","urls": [ "/signin-microsoft","/signin-google","/signin-facebook","/signin-twitter" ],{
"name": "sitemap","urls": [
"/Sitemap","/Sitemap/**"
],"strategy": "freshness"
}
}
],"navigationUrls": [
/* Specify what links should/should be handled by your angular app/index-file */
"/**","!/**/*.*","!/**/*__*","!/**/*__*/**","!/web/v2/Account/connect/**/**","!/web/v2/Account/add/**/**","!/api/**"
],"cacheConfig": {
"strategy": "freshness"
}
}
然后我添加了以下代码来检查新版本:
@Component({
selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit,OnDestroy {
constructor(private swUpdate: SwUpdate) {
//#region Check for updates
if (this.swUpdate.isEnabled) {
console.log('Updates enabled');
this.swUpdate.activated.subscribe((upd) => {
console.log('Update activated');
window.location.reload();
});
this.swUpdate.available.subscribe((upd) => {
console.log('Update available');
if (confirm('Do you want to install the new version of the app?')) {
console.log('Activating update');
this.swUpdate.activateUpdate();
}
},(error) => {
console.log(error);
});
this.swUpdate.checkForUpdate().then(() => {
console.log('Checking for updates');
}).catch((error) => {
console.log('Could not check for app updates',error);
});
}
//#endregion
}
ngOnInit() {
}
ngOnDestroy() {
}
}
您正在使用@angular/pwa。 但无论如何,现在每次发布新版本时,应用程序都会检查在线版本是否比缓存的版本更新......
我在安装更新之前使用了 confirm
提示,但您可能希望忽略它,或者以不同的方式处理它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。