とんかつ時々あんどーなつ

〜たとえ低空でも飛行していられるように〜

Angular の strict mode とはなんなのか

はじめに

この記事は Angular Advent Calendar 2020 の 1 日目の記事です。

今日は Angular CLI の v10 でオプションとして追加され v11 でプロンプトにも表示されるようになった strict mode について紹介します。

angular.jp

公式ドキュメントを見ると strict mode にすると静的解析でできることが増えたり、 ng update がより安全になると書かれています。 今から新規でアプリケーションを作る人にとっては、有効にしない理由はないのではないでしょうか?

ここでは具体的に変更になる箇所はどこなのかを見ていきます。

strict mode について

以下のように Angular アプリケーションを新規で作成します。ドキュメントにも記載があるように --strict オプションを付ける方法もありますが v11.x ではプロンプトで選択肢がでます。

npx @angular/cli new strict-mode --packageManager yarn
? Do you want to enforce stricter type checking and stricter bundle budgets in the workspace?
  This setting helps improve maintainability and catch bugs ahead of time.
  For more information, see https://angular.io/strict (y/N)

変更があるファイルは下記の 2 つです。

変更点

angular.json

schematics/angular:application

"@schematics/angular:application": {
  "strict": true
}

$ ng application で application を作成するときの schematics が strict true で設定されます。

budgets

build assets の size-budget がかなり厳しく制限されます。具体的には下記の表の通りですが、最大で 75% 減となります。 initial はアプリの初期サイズを指し、anyComponentStyle はいずれか 1 つのコンポーネントスタイルシートのサイズを指します。 maximumWarning で指定した閾値を超えると警告出て、maximumError で指定した閾値を超えるとエラーになります。

budget の種類 プロパティ default strict mode
initial maximumWarning 2MB 500KB
initial maximumError 5MB 1MB
anyComponentStyle maximumWarning 6KB 2KB
anyComponentStyle maximumError 10KB 4KB

tsconfig.json

Compiler Options

TypeScript Compiler Options の以下のルールが有効化されます。

ルール 説明
forceConsistentCasingInFileNames ファイル名の大文字 / 小文字の違いを区別する
strict すべての strict オプションをすべて有効にする
noImplicitReturns 関数内のすべての条件で return する必要がある
noFallthroughCasesInSwitch switch 文の fallthrough を許可しない

Angular Compiler Options

Angular Compiler Options の以下のルールが有効化されます。

ルール 説明
strictInjectionParameters DI するときにサポートされていない injection token を指定しているとエラーになる
strictInputAccessModifiers Input プロパティにバインディングするときに private/protected/readonly のアクセス修飾子を許容しない
strictTemplates テンプレート内の型チェックが strict モードになる

まとめ

個人的には assets の size-budgets がかなり厳し目の印象を受けましたが、その他はプロジェクト初期に有効化しておくとかなり恩恵を得られるのではないかと感じました。

おわり

明日は ringtail003 さんです。