LoginSignup
1
1

More than 5 years have passed since last update.

Angular2でCache Busting機能を実装する方法

Posted at

Angular2でCache Busting機能を実装する方法

実装方法

下記のSample.htmlに実装しているSystem.locateプロパティに定義したメソッドでjsのURLをリクエストする際にURLパラメータを付ける処理が実行されます。

注意点
Sample.htmlの様にCache Bustingを実装するとnode_modulesフォルダ内のファイルに対してもCache Bustingが機能してしまうので、デプロイした際にnode_modulesフォルダ内のファイルを一度は読み込んでしまいます。

Cache Bustingが有効なパターン

  1. sample.component.ts(変更前)で実装されているimportで外部ファイルを読み込む際にもURLパラメータが付与されCache Bustingが機能します。
  2. test.routing.tsのloadChildrenプロパティで遅延ロードしているsample.module.jsファイルのURIにはURLパラメータが付与されCache Bustingが機能します。

Cache Bustingが無効なパターン(有効にするには)

sample.component.ts(変更前)にはtemplateUrlのhtmlファイルのURIにはパラメータが付与されずCache Bustingは機能しません。なのでsample.component.ts(変更後)ように実装する事でURLパラメータを付与してCache Bustingを機能させましょう。

サンプルコード

Sample.html
<head>
    <script src="../node_modules/systemjs/dist/system.src.js"></script>
</head>
<body>
<script>
    var version: string = '001';
    System.cacheBust = '?v=' + version;

    var systemLocate = System.locate;
    System.locate = function(load) {
      return Promise.resolve(systemLocate.call(this, load)).then(function(address) {
        return address + System.cacheBust;
      });
    }

    window.CacheBusting = function(uri: string):string {
        return uri + System.cacheBust;
    }
</script>
</body>
sample.component.ts(変更前)
import { Component } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'my-sample',
  templateUrl: 'sample.component.html'
})
export class SampleComponent {}
sample.component.ts(変更後)
import { Component } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'my-sample',
  templateUrl: window.CacheBusting('sample.component.html')
})
export class SampleComponent {}
test.routing.ts
import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const testRoutes: Routes = [
  { path: 'Sample', loadChildren: './sample.module#SampleModule', }
];
@NgModule({
  imports: [
    RouterModule.forChild(testRoutes)
  ],
  exports: [
    RouterModule
  ]
})
export class TestRoutingModule {}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1