Angular を AWS Amplify にホスティングする

はじめに

AWS Amplify に入門してみます。
まずは Angular で作ったサイトを Amplify にホスティングする方法をまとめます。

Angular を AWS Amplify にホスティングする

Angular のサイトを作成、Amplify の導入、ホスティングの流れで行います。

Angular のサイトを作成

今回は amplify-example という名前でサイトを作成します。
手癖で materialflex-layout をインストールします。

$ ng new amplify-example --routing  --style=scss
$ cd amplify-example
$ ng add @angular/material
$ npm i -s @angular/flex-layout @angular/cdk
$ ng serve 
$ open http://localhost:4200

Amplify の導入

AWS Amplify のドキュメント にAngularへの導入方法があるのでそれに沿って進めていきます。

$ npm install aws-amplify aws-amplify-angular 

polyfills.ts に以下のコードを追加します。

(window as any).global = window;
(window as any).process = {
  env: { DEBUG: undefined },
};

Ivy についての注意書きがあります。
Ivy は Angular 8 時点では optIn なので Angular 9 が出てきたあたりでサポートされる感じですかね。

Please also note that the AWS Amplify Angular components do not yet support Ivy.

amplify の cli を global にインストールします。
amplify configure を実行することでAWS console が開かれIAMユーザーの作成を行います。
ドキュメントに動画があるので迷うことはなさそうです。

$ npm install -g @aws-amplify/cli
$ amplify configure
? region:  ap-northeast-1 
? user name:  amplify-XXXXX # IAM username
? accessKeyId:  ********** # accessKeyId
? secretAccessKey:  ******************** # secretAccessKey
? Profile Name:  default

Angular の project root で amplify init を行います。
project root に amplify というディレクトリができます。

$ amplify init
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project amplify-example
? Enter a name for the environment dev
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using angular
? Source Directory Path:  src
? Distribution Directory Path: dist/amplify-example
? Build Command:  ng build
? Start Command: ng serve

amplify に hosting してみます。 ここで PROD を選択すると S3に加えて CloudFront も立ち上がりHTTPS にて hosting されるようです。

$ amplify add hosting
? Select the environment setup: DEV (S3 only with HTTP)
? hosting bucket name amplify-example-XXXXXXXXXXX-hostingbucket
? index doc for the website index.html
? error doc for the website index.html

amplify publish コマンドにて実行されます。 実行するとCloudFormation がガチャガチャされます。今回は S3 のみですが。

$ amplify publish

Current Environment: dev

| Category | Resource name   | Operation | Provider plugin   |
| -------- | --------------- | --------- | ----------------- |
| Hosting  | S3AndCloudFront | Create    | awscloudformation |

Hosting endpoint という出力があるのでその URL で S3 に hosting されています。

f:id:nananao_dev:20191207221420p:plain

まとめ

Angular を AWS Amplify にホスティングする方法をまとめました。
AWS の構成は AWS cdk で一元管理したいので利用するか少し「悩みます。。

参考サイト

Angular+AWS Amplifyを試した - なになれ