如何防止Angular 2站点上的浏览器缓存?

时间:2016-09-22 19:54:33

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

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

主要是js文件的html / css文件似乎得到了正确的更新而没有给出太多麻烦。

6 个答案:

答案 0 :(得分:107)

angular-cli通过为build命令提供--output-hashing标记来解决这个问题。用法示例:

ng build --aot --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的用户,但它的工作非常出色,并且不需要任何代码更改或其他工具。

答案 1 :(得分:32)

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

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

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

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

并对一些字符进行子串,以便它只会在一小时后改变,例如:

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

希望这有帮助

答案 2 :(得分:14)

在每个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文件中的meta no缓存规则设置。

答案 3 :(得分:2)

结合使用@Jack的答案和@ranierbit的答案即可。

为--output-hashing设置ng build标志,以便:

ng build --output-hashing=all

然后在服务或您的应用中添加此类。moudle

@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
]

这应该防止客户端计算机在活动站点上缓存问题

答案 4 :(得分:1)

我也遇到过类似的问题,即index.html被浏览器缓存,或者由中间的CDN /代理更为棘手(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解决方案是针对角度4的,因此进行了一些细微的更改,因此我还将固定脚本放在此处:

VersionCheckService:

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 文件夹中,然后使用node ./build/post-build.js构建dist文件夹,然后使用ng build --prod运行脚本即可。

答案 5 :(得分:1)

将此添加到您的 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
}