Amplify CLIで既存のAWSリソースに接続する
AWS Amplify CLI(コマンドラインインターフェース)は、認証、データベース、ストレージなどのクラウドリソースをコマンドラインでアプリケーション用にプロビジョニングするシンプルなワークフローを提供します。
このガイドでは、Amplify CLIを使用して既に作成したバックエンドリソースに新しいReactウェブアプリを接続する方法を学びます。
ウェブアプリを既存のAWSリソースに接続する
このガイドでは、既存のReactアプリ用にAmplifyで作成されたAWSリソースに新しいReactウェブアプリを接続する手順を説明します。既存のアプリがない場合は、このReactチュートリアルに従って、Amplify Auth、API、およびHostingリソースを使用するTo-Doアプリを作成できます。
開始する前に、以下が必要です:
- 既存のReactアプリ
- AWSアカウント:アカウントがない場合は、AWSEnvironmentの設定チュートリアルに従って、簡単な概要を取得してください。
- インストールおよび構成されたAmplify CLI。
- テキストエディタ。このガイドではVS Codeを使用しますが、好みのIDEを使用できます。
AWSバックエンド詳細を検索する
バックエンドリソースを新しいアプリに接続する前に、まず既存のアプリ用にプロビジョニングされたAWS環境の詳細を見つける必要があります。
ステップ1: 既存のアプリで、<Your-App>/amplify/team-provider-info.jsonファイルを開きます。

ステップ2: team-provider-info.jsonファイルで、以下を記録します:
- 使用する環境
- 必要な環境の
AmplifyAppId

Reactアプリを作成する
必要なバックエンド詳細を収集したので、新しいReactアプリの構築を開始できます。
ステップ1: ターミナルで以下のコマンドを実行して、Reactアプリを作成します。
npx create-react-app react-amplify-connectステップ2: ターミナルで以下のコマンドを実行して、新しく作成されたReactアプリをVS Codeで開きます。
cd react-amplify-connectcode . -rステップ3: アプリのルートフォルダに移動し、ターミナルで以下のコマンドを実行してAmplifyバックエンドをアプリにインポートします。
amplify pull --appId <The_App_ID> --envName <The_App_Env>ステップ4: AWS認証方法を選択します。この例では、AWSプロファイルを使用しています。選択したプロファイルがAWSリソースへのアクセスと変更に必要な権限を持っていることを確認してください。AWSプロファイルの設定の詳細については、Amplify CLIの構成を参照してください。
デフォルト値を受け入れ、「modifying this backend」質問にはいと答えることを確認します。Amplify CLIはバックエンドを初期化し、プロジェクトをクラウドに接続します。
? Select the authentication method you want to use: AWS profile
For more information on AWS Profiles, see:https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html
? Please choose the profile you want to use AwsWest1Amplify AppID found: dfn3u8j1nvzjc. Amplify App name is: reactamplifiedBackend environment dev found in Amplify Console app: reactamplified? Choose your default editor: Visual Studio Code✔ Choose the type of app that you're building · javascriptPlease tell us about your project? What javascript framework are you using react? Source Directory Path: src? Distribution Directory Path: build? Build Command: npm run-script build? Start Command: npm run-script start? Do you plan on modifying this backend? Yes⠋ Fetching updates to backend environment: dev from the cloud.⚠️ WARNING: your GraphQL API currently allows public create, read, update, and delete access to all models via an API Key. To configure PRODUCTION-READY authorization rules, review: https://docs.amplify.aws/cli/graphql/authorization-rules
⠇ Fetching updates to backend environment: dev from the cloud.✅ GraphQL schema compiled successfully.
Edit your schema at /Users/malakamm/development/react-amplify-connect/amplify/backend/api/reactamplified/schema.graphql or place .graphql files in a directory at /Users/malakamm/development/react-amplify-connect/amplify/backend/api/reactamplified/schema✔ Successfully pulled backend environment dev from the cloud.Browserslist: caniuse-lite is outdated. Please run: npx update-browserslist-db@latest Why you should do it regularly: https://github.com/browserslist/update-db#readme✅
✅ Successfully pulled backend environment dev from the cloud.Run 'amplify pull' to sync future upstream changes.Amplify CLIは、Amplifyプロジェクトとバックエンド詳細を含むamplifyという名前の新しいフォルダをアプリのルートフォルダに追加します。

ステップ5:以下のコマンドを使用してGraphQLステートメントを生成します。
amplify codegen addステップ6: プロンプトのデフォルト値を受け入れます。
? Choose the code generation language target javascript? Enter the file name pattern of graphql queries, mutations and subscriptions src/graphql/**/*.js? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions Yes? Enter maximum statement depth [increase from default if your schema is deeply nested] 2✔ Generated GraphQL operations successfully and saved at src/graphqlCLIは、GraphQLステートメントを含むgraphqlという名前の新しいフォルダをアプリのルートフォルダに追加します。

ステップ7: 以下のコマンドを実行して、aws-amplifyおよび@aws-amplify/ui-reactパッケージをインストールします。
npm install aws-amplify @aws-amplify/ui-reactステップ8: App.jsファイルを以下のコードで更新して、Amplify UIを使用したログインフロー、To-Doを作成するボタンを備えたフォーム、およびTo-Doのリストをフェッチしてレンダリングする方法を作成します。
import React, { useEffect, useState } from 'react'import { Amplify, API, graphqlOperation } from 'aws-amplify'import { createTodo } from './graphql/mutations'import { listTodos } from './graphql/queries'import { withAuthenticator, Button, Heading } from '@aws-amplify/ui-react';import '@aws-amplify/ui-react/styles.css';
import awsExports from "./aws-exports";Amplify.configure(awsExports);
const initialState = { name: '', description: '' }
const App = ({ signOut, user }) => { const [formState, setFormState] = useState(initialState) const [todos, setTodos] = useState([])
useEffect(() => { fetchTodos() }, [])
function setInput(key, value) { setFormState({ ...formState, [key]: value }) }
async function fetchTodos() { try { const todoData = await API.graphql(graphqlOperation(listTodos)) const todos = todoData.data.listTodos.items setTodos(todos) } catch (err) { console.log('error fetching todos') } }
async function addTodo() { try { if (!formState.name || !formState.description) return const todo = { ...formState } setTodos([...todos, todo]) setFormState(initialState) await API.graphql(graphqlOperation(createTodo, {input: todo})) } catch (err) { console.log('error creating todo:', err) } }
return ( <div style={styles.container}> <Heading level={1}>Hello {user.username}</Heading> <Button onClick={signOut} style={styles.button}>Sign out</Button> <h2>Amplify Todos</h2> <input onChange={event => setInput('name', event.target.value)} style={styles.input} value={formState.name} placeholder="Name" /> <input onChange={event => setInput('description', event.target.value)} style={styles.input} value={formState.description} placeholder="Description" /> <button style={styles.button} onClick={addTodo}>Create Todo</button> { todos.map((todo, index) => ( <div key={todo.id ? todo.id : index} style={styles.todo}> <p style={styles.todoName}>{todo.name}</p> <p style={styles.todoDescription}>{todo.description}</p> </div> )) } </div> )}
const styles = { container: { width: 400, margin: '0 auto', display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: 20 }, todo: { marginBottom: 15 }, input: { border: 'none', backgroundColor: '#ddd', marginBottom: 10, padding: 8, fontSize: 18 }, todoName: { fontSize: 20, fontWeight: 'bold' }, todoDescription: { marginBottom: 0 }, button: { backgroundColor: 'black', color: 'white', outline: 'none', fontSize: 18, padding: '12px 0px' }}
export default withAuthenticator(App);ステップ9: 以下のコマンドを使用してアプリを実行します。
npm startステップ10: アプリのUIを次のように変更して、To-Doフォームのプレースホルダーテキストを更新し、ユーザーのメールをハロー メッセージに使用します。
... return ( <div style={styles.container}> <Heading level={1}>Hello {*user*.attributes.email}</Heading> <Button onClick={signOut} style={styles.button}>Sign out</Button> <h2>Amplify Todos</h2> <input onChange={event => setInput('name', event.target.value)} style={styles.input} value={formState.name} placeholder="ToDo Name" /> <input onChange={event => setInput('description', event.target.value)} style={styles.input} value={formState.description} placeholder="ToDo Description" /> <button style={styles.button} onClick={addTodo}>Create Todo</button> { todos.map((todo, index) => ( <div key={todo.id ? todo.id : index} style={styles.todo}> <p style={styles.todoName}>{todo.name}</p> <p style={styles.todoDescription}>{todo.description}</p> </div> )) } </div> )....App.jsファイルは次のコードスニペットのようになります。
import React, { useEffect, useState } from 'react'import { Amplify, API, graphqlOperation } from 'aws-amplify'import { createTodo } from './graphql/mutations'import { listTodos } from './graphql/queries'import { withAuthenticator, Button, Heading } from '@aws-amplify/ui-react';import '@aws-amplify/ui-react/styles.css';
import awsExports from "./aws-exports";Amplify.configure(awsExports);
const initialState = { name: '', description: '' }
const App = ({ signOut, user }) => { const [formState, setFormState] = useState(initialState) const [todos, setTodos] = useState([])
useEffect(() => { fetchTodos() }, [])
function setInput(key, value) { setFormState({ ...formState, [key]: value }) }
async function fetchTodos() { try { const todoData = await API.graphql(graphqlOperation(listTodos)) const todos = todoData.data.listTodos.items setTodos(todos) } catch (err) { console.log('error fetching todos') } }
async function addTodo() { try { if (!formState.name || !formState.description) return const todo = { ...formState } setTodos([...todos, todo]) setFormState(initialState) await API.graphql(graphqlOperation(createTodo, {input: todo})) } catch (err) { console.log('error creating todo:', err) } }
return ( <div style={styles.container}> <Heading level={1}>Hello {user.attributes.email}</Heading> <Button onClick={signOut} style={styles.button}>Sign out</Button> <h2>Amplify Todos</h2> <input onChange={event => setInput('name', event.target.value)} style={styles.input} value={formState.name} placeholder="ToDo Name" /> <input onChange={event => setInput('description', event.target.value)} style={styles.input} value={formState.description} placeholder="ToDo Description" /> <button style={styles.button} onClick={addTodo}>Create Todo</button> { todos.map((todo, index) => ( <div key={todo.id ? todo.id : index} style={styles.todo}> <p style={styles.todoName}>{todo.name}</p> <p style={styles.todoDescription}>{todo.description}</p> </div> )) } </div> )}
const styles = { container: { width: 400, margin: '0 auto', display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: 20 }, todo: { marginBottom: 15 }, input: { border: 'none', backgroundColor: '#ddd', marginBottom: 10, padding: 8, fontSize: 18 }, todoName: { fontSize: 20, fontWeight: 'bold' }, todoDescription: { marginBottom: 0 }, button: { backgroundColor: 'black', color: 'white', outline: 'none', fontSize: 18, padding: '12px 0px' }}
export default withAuthenticator(App);ステップ11: 以下のコマンドを使用して変更を発行します。Amplify CLIは変更を発行し、アプリURLを表示します。
amplify publish
ステップ12: URLを使用してブラウザーでアプリを実行します。
結論
おめでとうございます!新しいReactアプリは、AWS Amplifyを通じて別のアプリからのAWSリソースに接続されました。この統合により、アプリはユーザー管理用の認証リソース、Amazon DynamoDBで支援されたスケーラブルなGraphQL API、およびアプリをクラウドに発行するためのホスティングサービスにアクセスできます。
リソースをクリーンアップする
このデモアプリの実験が終わったら、予期しない費用の発生を避けるためにバックエンドリソースを削除することをお勧めします。これは、アプリのルートフォルダで以下のコマンドを実行することで行えます。
amplify deleteこのデモアプリを本番対応アプリに拡張したい場合は、認可やストレージなどの追加リソースを追加する必要がある場合があります。Build&connectバックエンドセクションを参照して、他のバックエンドリソースを追加および接続する方法に関するガイドを確認してください。