この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
こんにちは!DA(データアナリティクス)事業本部 サービスソリューション部の大高です。
先日、Amplify UIの新しいAuthenticatorコンポーネントが、リリースされました。
今回は、こちらのコンポーネントをAngularで試してみたいと思います。
前提
Angular CLIやNodeなどは以下の通りのバージョンを利用しています。
% ng --version
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular CLI: 13.0.3
Node: 16.13.0
Package Manager: npm 8.1.0
OS: darwin arm64
Angular:
...
Package Version
------------------------------------------------------
@angular-devkit/architect 0.1300.3 (cli-only)
@angular-devkit/core 13.0.3 (cli-only)
@angular-devkit/schematics 13.0.3 (cli-only)
@schematics/angular 13.0.3 (cli-only)
Angularプロジェクトの作成
適当なフォルダで、以下のように新規プロジェクトを作成します。
% ng new hello-new-amplify-ui
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? SCSS [ https://sass-lang.com
/documentation/syntax#scss ]
CREATE hello-new-amplify-ui/README.md (1063 bytes)
(...snip...)
CREATE hello-new-amplify-ui/src/app/app.component.ts (225 bytes)
✔ Packages installed successfully.
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint:
hint: git config --global init.defaultBranch <name>
hint:
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint:
hint: git branch -m <name>
Successfully initialized git.
プロジェクトを作成したら、簡単に動作確認しておきます。
% cd hello-new-amplify-ui
% yarn start
問題ないですね。
Amplify UIの導入
では、Amplify UIを導入していきます。Amplify UIについては、新しく以下のサイトができているのでこちらの「Getting started」を見ながら導入していきます。
インストール
まずは、下記のコマンドでAngularプロジェクトにAmplify UIをインストールします。
% yarn add aws-amplify @aws-amplify/ui-angular
スタイルの追加
インストールができたら、スタイルの追加をしておきます。
src/styles.scss
/* You can add global styles to this file, and also import other style files */
@import '~@aws-amplify/ui-angular/theme.css';
Shimの設定
global
とprocess
のShim対応として、以下のコードを追加します。
src/polyfills.ts
(window as any).global = window;
(window as any).process = {
env: { DEBUG: undefined },
};
Strictモードのエラー対応
strictモードが有効になっている場合、以下のようなビルドエラーが発生します。
Error: node_modules/@aws-amplify/ui-angular/node_modules/@aws-amplify/ui/dist/index.d.ts:37:44 - error TS2339: Property 'loginMechanisms' does not exist on type '{ loginMechanisms?: ("username" | "email" | "phone_number")[] | undefined; signUpAttributes?: SignUpAttribute[] | undefined; socialProviders?: SocialProvider[] | undefined; } | undefined'.
37 loginMechanisms: AuthContext['config']['loginMechanisms'];
~~~~~~~~~~~~~~~~~
Error: node_modules/@aws-amplify/ui-angular/node_modules/@aws-amplify/ui/dist/index.d.ts:38:44 - error TS2339: Property 'socialProviders' does not exist on type '{ loginMechanisms?: ("username" | "email" | "phone_number")[] | undefined; signUpAttributes?: SignUpAttribute[] | undefined; socialProviders?: SocialProvider[] | undefined; } | undefined'.
38 socialProviders: AuthContext['config']['socialProviders'];
~~~~~~~~~~~~~~~~~
今回は簡易なワークアラウンドとして、strictモードを無効にしておきます。
tsconfig.json
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": false,
"noImplicitOverride": true,
(...snip...)
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
CommonJS or AMD dependencies のWarning対応
Angular 9からビルド時にCommonJSのモジュールが含まれていると警告を表示してくれるようになりました。
この警告が気になる場合には、本質的な解決ではありませんが以下のようにangular.json
に警告を除外するように設定することで警告表示を抑制できます。
なお、私が試した段階ではcamelcase-keys
とulid
も追記するとよさそうでした。
画面にAuthenticatorコンポーネントを表示させてみる
Aumplify UIのインストールができたので、実際に画面にAuthenticatorコンポーネントを表示させてみましょう。
下記のコンポーネントのガイドを参考にやっていきます。
app.module.ts
以下のように修正します。
src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AmplifyAuthenticatorModule } from '@aws-amplify/ui-angular';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
AmplifyAuthenticatorModule
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
app.component.html
デフォルトのコンテンツを消して、以下のように書き換えます。
src/app/app.component.html
<amplify-authenticator>
<ng-template amplifySlot="authenticated" let-user="user" let-signOut="signOut">
<h2>Welcome, {{ user.username }}!</h2>
<button (click)="signOut()">Sign Out</button>
</ng-template>
</amplify-authenticator>
<router-outlet></router-outlet>
表示してみる
これで準備ができたので、とりあえず起動して表示してみます。
% yarn start
ログイン画面が表示できました!
また、以下のエントリで紹介したようにCognito側の設定を行い、environment.ts
の設定情報をapp.module.ts
で読み込むように設定すると、実際にログインすることもできます。
ログインすると、以下のように表示されます。
なお、手動で設定しても良いのですがCognito側の設定はAmplify CLIを利用して設定するのが定石かと思います。今回のアップデートでも「Zero Configuration」として推しポイントになっており、コード変更なしでの設定が可能となっています。
まとめ
以上、Amplify UIの新しいAuthenticatorコンポーネントをAngularで試してみました。
個人的に特に嬉しいポイントとして、パスワードマネージャーの1Passwordが使えるようになっているのが最高でした。
以前はShadow DOMを利用している関係上、ブラウザ拡張機能の1Passwordが利用できなかったのですが、Shadow DOMを利用しない作りに変わったため、1Passwordが利用できるようになってるようです。
また、「日本語化をしたいな」とか「Create Account の箇所を消したいな」とか色々と気になる点もあるので、できればこちらも別途調べてまとめたいと思います。
どなたかのお役に立てば幸いです。それでは!