Angular 应用程序必须在新部署后清除缓存

问题描述:

我们有一个 Angular 6 应用程序.它在 Nginx 上提供.并且 SSL 已开启.

We have an Angular 6 application. It’s served on Nginx. And SSL is on.

当我们部署新代码时,大多数新功能都可以正常工作,但对于某些更改则不行.例如,如果前端开发人员更新服务连接并进行部署,用户必须打开隐身窗口或清除缓存才能看到新功能.

When we deploy new codes, most of new features work fine but not for some changes. For example, if the front-end developers update the service connection and deploy it, users have to open incognito window or clear cache to see the new feature.

哪些类型的更改不会自动更新?为什么他们与其他人不同?

What type of changes are not updated automatically? Why are they different from others?

避免该问题的常见解决方案是什么?

What’s the common solution to avoid the issue?

问题是当静态文件被缓存时,它可以在最终过期之前存储很长时间.如果您更新网站,这可能会很麻烦,但是,由于文件的缓存版本存储在访问者的浏览器中,他们可能无法看到所做的更改.

The problem is When a static file gets cached it can be stored for very long periods of time before it ends up expiring. This can be an annoyance in the event that you make an update to a site, however, since the cached version of the file is stored in your visitors’ browsers, they may be unable to see the changes made.

Cache-busting 通过使用独特的文件版本标识符告诉浏览器该文件的新版本可用.因此浏览器不会从缓存中检索旧文件,而是向源服务器请求新文件.

Cache-busting solves the browser caching issue by using a unique file version identifier to tell the browser that a new version of the file is available. Therefore the browser doesn’t retrieve the old file from cache but rather makes a request to the origin server for the new file.

Angular cli 通过为构建命令提供 --output-hashing 标志来解决这个问题.

Angular cli resolves this by providing an --output-hashing flag for the build command.

查看官方文档:https://angular.io/cli/build

示例(旧版本)

ng build --prod --aot --output-hashing=all

以下是您可以在 --output-hashing

  • none:不执行散列
  • 媒体:仅向通过 [url|file]-loaders 处理的文件添加哈希
  • bundles:只向输出包添加哈希
  • all:向媒体和捆绑包添加哈希

更新

对于较新版本的 angular(例如 Angular 10),命令现已更新:

For the newer version of angular ( for example Angular 10) the command is now updated :

ng build --prod --aot --outputHashing=all