首页 > 解决方案 > Angular 12 应用程序仍在使用 output-hashing=all 进行缓存

问题描述

我有一个 Angular 12 应用程序,它具有不同的构建环境(dev/staging/prod),并且我已经在 in 上配置了输出散列angular.json

"configurations": {
    "production": {
        "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ],
          "optimization": true,
          "outputHashing": "all" <-----

输出文件确实包含哈希,但除非我在浏览器中进行硬刷新,否则我仍然看到旧版本。

main.07258fce7f84f8b6013e.js
polyfills.4cc5b416b55531e38cd8.js
runtime.734c276f75a5d81bc54b.js

登录页面只是一个登录表单,但版本显示在表单下方。它显示旧版本,直到浏览器中的硬刷新,此时它正确显示新版本。

这是因为index.html与所有旧的 JS 引用一起被缓存了吗?

如果是这样,我该如何缓存这个?

标签: angular

解决方案


如果您使用的是服务工作者(例如@angular/pwa安装@angular/service-worker的),那么您的整个 Angular 应用程序都会被浏览器缓存。这包括index.html+ 所有 javascript 文件 + 所有样式表。

要将应用程序的新版本推送给用户,您必须做两件事:

ngsw-config.json在每个新版本上更新您的:

{
    "version": 1, // Or ascending
    ...
}

致电SwUpdate

constructor(private swUpdate: SwUpdate) {
    ...

    //#region Check for updates
    if (this.swUpdate.isEnabled) {
      this.swUpdate.activated.subscribe((upd) => {
        window.location.reload();
      });
      this.swUpdate.available.subscribe((upd) => {
        this.swUpdate.activateUpdate();
      }, (error) => {
        console.error(error);
      });
      this.swUpdate.checkForUpdate().then(() => {
      }).catch((error) => {
        console.error('Could not check for app updates', error);
      });
    }
    //#endregion
}

这是一个例子


推荐阅读