当您在部署新版本的Angular应用程序后,如果在浏览器中仍然看到旧版本的应用程序,即使在清除缓存之后也是如此,这通常是由于以下几个原因造成的:
以下是一些解决这个问题的步骤:
确保在部署新版本时,Service Worker也被更新。可以通过以下方式强制更新Service Worker:
import { Injectable } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';
@Injectable({
providedIn: 'root'
})
export class UpdateService {
constructor(private swUpdate: SwUpdate) {
this.swUpdate.available.subscribe(event => {
console.log('current version is', event.current);
console.log('available version is', event.available);
this.swUpdate.activateUpdate().then(() => document.location.reload());
});
}
}
在构建过程中,为静态资源添加版本哈希,确保每次部署后资源的URL都发生变化。可以在angular.json
中配置:
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"serviceWorker": true,
"ngswConfigPath": "src/ngsw-config.json"
}
}
在部署新版本后,可以通过以下方式清除Service Worker缓存:
import { Injectable } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';
@Injectable({
providedIn: 'root'
})
export class ClearCacheService {
constructor(private swUpdate: SwUpdate) {
this.swUpdate.available.subscribe(event => {
this.swUpdate.activateUpdate().then(() => {
navigator.serviceWorker.getRegistrations().then(registrations => {
for (const registration of registrations) {
registration.unregister();
}
}).then(() => document.location.reload());
});
});
}
}
确保服务器配置了适当的HTTP缓存头,以便浏览器能够正确处理资源的缓存。例如,在Nginx中可以这样配置:
location / {
try_files $uri $uri/ /index.html;
add_header Cache-Control "no-cache, no-store, must-revalidate";
add_header Pragma "no-cache";
add_header Expires 0;
}
通过以上步骤,您应该能够解决浏览器在部署新版本Angular应用程序后仍然显示旧版本的问题。
没有搜到相关的文章