【问题标题】:How to prevent Browser cache on Angular 2 site?如何防止 Angular 2 站点上的浏览器缓存?
【发布时间】:2017-01-31 13:10:39
【问题描述】:

我们目前正在开发一个定期更新的新项目,我们的一位客户每天都在使用该项目。该项目正在使用 Angular 2 开发,我们面临缓存问题,即我们的客户没有看到他们机器上的最新更改。

主要是 js 文件的 html/css 文件似乎可以正确更新而没有带来太多麻烦。

【问题讨论】:

  • 非常好的问题。我也有同样的问题。解决这个问题的最佳方法是什么?这可以通过 gulp 或任何类似的工具来发布 Angular 2 应用程序吗?
  • @jump4791 最好的方法是使用 webpack 并使用生产设置编译项目。我目前正在使用这个 repo,只需按照步骤操作,你应该会很好:github.com/AngularClass/angular2-webpack-starter
  • 我也有同样的问题。
  • 我知道这是一个老问题,但我想为遇到此问题的任何人添加我找到的解决方案。使用ng build 构建时,添加-prod 标记会将哈希添加到生成的文件名。这会强制重新加载除index.html 之外的所有内容。 This github post 有一些关于让它重新加载的提示。
  • index.html 是根本原因。因为它没有哈希码,所以当它被缓存时,其他所有东西都从缓存中使用。

标签: caching angular browser-cache cache-control angular2-template


【解决方案1】:

angular-cli 通过为build 命令提供--output-hashing 标志来解决此问题(版本6/7,更高版本请参见here)。示例用法:

ng build --output-hashing=all

Bundling & Tree-Shaking 提供了一些细节和上下文。运行ng help build,记录标志:

--output-hashing=none|all|media|bundles (String)

Define the output filename cache-busting hashing mode.
aliases: -oh <value>, --outputHashing <value>

虽然这仅适用于angular-cli 的用户,但它运行良好,不需要任何代码更改或额外的工具。

更新

许多 cmets 有帮助并且正确指出此答案向 .js 文件添加了哈希,但对 index.html 没有任何作用。因此,在ng build 缓存破坏.js 文件之后,index.html 完全有可能保持缓存状态。

此时我将推迟到How do we control web page caching, across all browsers?

【讨论】:

  • 这是正确的方法,应该是选择的答案!
  • 这不适用于我们的应用程序。太糟糕了,带有查询字符串参数的 templateUrl 不适用于 CLI
  • 如果您的 index.html 被浏览器缓存,这将不起作用,因此不会看到您的 javascript 资源的新哈希名称。我认为这与@Rossco 给出的答案相结合是有道理的。使其与发送的 HTTP 标头保持一致也是有意义的。
  • @stryba 这就是为什么应该以不同方式处理 html 缓存的原因。您应该指定 Cache-Control、Pragma 和 Expires 响应标头,以便不进行缓存。如果您使用的是后端框架,这很容易,但我相信您也可以在 Apache 的 .htaccess 文件中处理这个问题(尽管了解它在 nginx 中的工作原理)。
  • 这个答案为 js 文件添加了一个哈希,这很棒。但正如 stryba 所说,您还需要确保 index.html 没有被缓存。您不应该使用 html 元标记来执行此操作,而应使用响应标头 cache-control: no-cache (或其他用于更花哨缓存策略的标头)。
【解决方案2】:

找到了一种方法,只需添加一个查询字符串来加载您的组件,如下所示:

@Component({
  selector: 'some-component',
  templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`,
  styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`]
})

这应该强制客户端加载服务器的模板副本而不是浏览器的副本。 如果您希望它仅在一段时间后刷新,您可以改用此 ISOString:

new Date().toISOString() //2016-09-24T00:43:21.584Z

并且对一些字符进行子串化,这样它只会在一个小时后改变,例如:

new Date().toISOString().substr(0,13) //2016-09-24T00

希望对你有帮助

【讨论】:

  • 所以我的实现实际上并没有成功。缓存是一个奇怪的问题。有时有效,有时无效。哦,间歇性问题的美丽。所以我实际上调整了你的答案:templateUrl: './app/shared/menu/menu.html?v=' + Math.random()
  • 我的 templateUrls 得到 404。例如:GET localhost:8080/app.component.html/?v=0.0.1-alpha 404(未找到)知道为什么吗?
  • @Rikku121 不,它没有。它实际上没有 / 在 url 中。我发表评论时可能不小心添加了它
  • 即使没有代码更改,每次都破坏缓存时,缓存有什么意义?
  • ng build --aot --build-optimizer=true --base-href=// 给出错误 --- 无法解析资源 ./login.component.html?v =${new Date().getTime()}
【解决方案3】:

在每个 html 模板中,我只需在顶部添加以下元标记:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

据我了解,每个模板都是独立的,因此它不会继承 index.html 文件中设置的元缓存规则。

【讨论】:

  • 我们已经切换到 webpack 有一段时间了,它负责缓存破坏我们的 Angular 应用程序。很高兴知道您的解决方案有效。谢谢
  • 对我也有影响
【解决方案4】:

@Jack 的答案和@ranierbit 的答案的组合应该可以解决问题。

为 --output-hashing 设置 ng 构建标志:

ng build --output-hashing=all

然后在服务或app.module中添加此类

@Injectable()
export class NoCacheHeadersInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler) {
        const authReq = req.clone({
            setHeaders: {
                'Cache-Control': 'no-cache',
                 Pragma: 'no-cache'
            }
        });
        return next.handle(authReq);    
    }
}

然后将其添加到您的app.module 中的提供商:

providers: [
  ... // other providers
  {
    provide: HTTP_INTERCEPTORS,
    useClass: NoCacheHeadersInterceptor,
    multi: true
  },
  ... // other providers
]

这应该可以防止客户端机器在实时站点上出现缓存问题

【讨论】:

    【解决方案5】:

    浏览器缓存 index.html 或者中间 cdn/proxy 更棘手(F5 无法帮助您)时,我遇到了类似的问题。

    我寻找了一个 100% 验证客户端具有最新 index.html 版本的解决方案,幸运的是我找到了 Henrik Peinar 的这个解决方案:

    https://blog.nodeswat.com/automagic-reload-for-clients-after-deploy-with-angular-4-8440c9fdd96c

    该解决方案还解决了客户端在浏览器打开数天的情况下,客户端每隔一段时间检查更新并在部署了较新版本时重新加载的情况。

    解决方案有点棘手,但效果很好:

    • 利用ng cli -- prod 生成散列文件的事实,其中一个名为 main.[hash].js
    • 创建一个包含该哈希的 version.json 文件
    • 创建一个角度服务 VersionCheckService 来检查 version.json 并在需要时重新加载。
    • 请注意,部署后运行的 js 脚本会为您创建 version.json 并替换 Angular 服务中的哈希,因此无需手动操作,而是运行 post-build.js

    由于 Henrik Peinar 解决方案是针对 Angular 4 的,因此有一些细微的变化,我也将固定脚本放在这里:

    版本检查服务:

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable()
    export class VersionCheckService {
        // this will be replaced by actual hash post-build.js
        private currentHash = '{{POST_BUILD_ENTERS_HASH_HERE}}';
    
        constructor(private http: HttpClient) {}
    
        /**
         * Checks in every set frequency the version of frontend application
         * @param url
         * @param {number} frequency - in milliseconds, defaults to 30 minutes
         */
        public initVersionCheck(url, frequency = 1000 * 60 * 30) {
            //check for first time
            this.checkVersion(url); 
    
            setInterval(() => {
                this.checkVersion(url);
            }, frequency);
        }
    
        /**
         * Will do the call and check if the hash has changed or not
         * @param url
         */
        private checkVersion(url) {
            // timestamp these requests to invalidate caches
            this.http.get(url + '?t=' + new Date().getTime())
                .subscribe(
                    (response: any) => {
                        const hash = response.hash;
                        const hashChanged = this.hasHashChanged(this.currentHash, hash);
    
                        // If new version, do something
                        if (hashChanged) {
                            // ENTER YOUR CODE TO DO SOMETHING UPON VERSION CHANGE
                            // for an example: location.reload();
                            // or to ensure cdn miss: window.location.replace(window.location.href + '?rand=' + Math.random());
                        }
                        // store the new hash so we wouldn't trigger versionChange again
                        // only necessary in case you did not force refresh
                        this.currentHash = hash;
                    },
                    (err) => {
                        console.error(err, 'Could not get version');
                    }
                );
        }
    
        /**
         * Checks if hash has changed.
         * This file has the JS hash, if it is a different one than in the version.json
         * we are dealing with version change
         * @param currentHash
         * @param newHash
         * @returns {boolean}
         */
        private hasHashChanged(currentHash, newHash) {
            if (!currentHash || currentHash === '{{POST_BUILD_ENTERS_HASH_HERE}}') {
                return false;
            }
    
            return currentHash !== newHash;
        }
    }
    

    更改为主 AppComponent:

    @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
        constructor(private versionCheckService: VersionCheckService) {
    
        }
    
        ngOnInit() {
            console.log('AppComponent.ngOnInit() environment.versionCheckUrl=' + environment.versionCheckUrl);
            if (environment.versionCheckUrl) {
                this.versionCheckService.initVersionCheck(environment.versionCheckUrl);
            }
        }
    
    }
    

    发挥神奇作用的构建后脚本 post-build.js:

    const path = require('path');
    const fs = require('fs');
    const util = require('util');
    
    // get application version from package.json
    const appVersion = require('../package.json').version;
    
    // promisify core API's
    const readDir = util.promisify(fs.readdir);
    const writeFile = util.promisify(fs.writeFile);
    const readFile = util.promisify(fs.readFile);
    
    console.log('\nRunning post-build tasks');
    
    // our version.json will be in the dist folder
    const versionFilePath = path.join(__dirname + '/../dist/version.json');
    
    let mainHash = '';
    let mainBundleFile = '';
    
    // RegExp to find main.bundle.js, even if it doesn't include a hash in it's name (dev build)
    let mainBundleRegexp = /^main.?([a-z0-9]*)?.js$/;
    
    // read the dist folder files and find the one we're looking for
    readDir(path.join(__dirname, '../dist/'))
      .then(files => {
        mainBundleFile = files.find(f => mainBundleRegexp.test(f));
    
        if (mainBundleFile) {
          let matchHash = mainBundleFile.match(mainBundleRegexp);
    
          // if it has a hash in it's name, mark it down
          if (matchHash.length > 1 && !!matchHash[1]) {
            mainHash = matchHash[1];
          }
        }
    
        console.log(`Writing version and hash to ${versionFilePath}`);
    
        // write current version and hash into the version.json file
        const src = `{"version": "${appVersion}", "hash": "${mainHash}"}`;
        return writeFile(versionFilePath, src);
      }).then(() => {
        // main bundle file not found, dev build?
        if (!mainBundleFile) {
          return;
        }
    
        console.log(`Replacing hash in the ${mainBundleFile}`);
    
        // replace hash placeholder in our main.js file so the code knows it's current hash
        const mainFilepath = path.join(__dirname, '../dist/', mainBundleFile);
        return readFile(mainFilepath, 'utf8')
          .then(mainFileData => {
            const replacedFile = mainFileData.replace('{{POST_BUILD_ENTERS_HASH_HERE}}', mainHash);
            return writeFile(mainFilepath, replacedFile);
          });
      }).catch(err => {
        console.log('Error with post build:', err);
      });
    

    只需将脚本放在(新)build 文件夹中,在使用 ng build --prod 构建 dist 文件夹后使用 node ./build/post-build.js 运行脚本

    【讨论】:

      【解决方案6】:

      将此添加到您的 nginx 中

      location ~ /index.html|.*\.json$ {
              expires -1;
              add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
          }
      
      location ~ .*\.css$|.*\.js$ {
         add_header Cache-Control 'max-age=31449600'; # one year
      }
      
      location / {
          try_files $uri $uri/ /index.html?$args;
          add_header Cache-Control 'max-age=86400'; # one day
      }
      

      【讨论】:

      • 如果我不使用 NGINX 怎么办?
      • 我想知道为什么人们没有投票赞成您的答案。谢了哥们。这个 index.html 弄得一团糟,ngnix 是处理它的好方法,幸运的是我在后端使用相同的
      【解决方案7】:

      您可以使用 HTTP 标头控制客户端缓存。这适用于任何 Web 框架。

      您可以设置这些标头的指令,以便对启用|禁用缓存的方式和时间进行细粒度控制:

      • Cache-Control
      • Surrogate-Control
      • Expires
      • ETag(非常好)
      • Pragma(如果你想支持旧浏览器)

      良好的缓存在所有计算机系统中都很好,但非常复杂。请查看https://helmetjs.github.io/docs/nocache/#the-headers 了解更多信息。

      【讨论】:

        【解决方案8】:

        当您使用 ng build 构建应用程序时,您应该使用以下标志:

        --outputHashing=all
        

        这是为了启用缓存清除。

        Cache-busting 通过使用唯一的文件版本标识符来告诉浏览器该文件的新版本可用,从而解决了浏览器缓存问题。因此,浏览器不会从缓存中检索旧文件,而是向源服务器请求新文件。

        因此,一种方法是运行它:

        示例(旧版本)

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

        下面是你可以传入--output-hashing的选项

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

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

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

        您可以在此处阅读有关构建选项标志的更多信息。 https://angular.io/cli/build

        如果您不希望在运行 ng build 时附加标志,则应在 angular.json 文件的配置中设置它们。

        "configurations": {
          "production": {
           "optimization": true,
            "outputHashing": "all",
             .
             .
             .
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2019-05-30
          • 1970-01-01
          • 1970-01-01
          • 2023-03-21
          • 1970-01-01
          • 1970-01-01
          • 2011-04-28
          • 1970-01-01
          • 2017-02-06
          相关资源
          最近更新 更多