反应 + AWS Amplify的初创企业

我正在简单地记录着React + AWS Amplify的教程笔记。基本上,我按照上述文章中的步骤进行,同时将遇到的问题记录下来。文章链接:https://www.cresco.co.jp/blog/entry/20393/

创建React应用程序

    以下コマンドでアプリを作成
npx create-react-app todo

打开应用

cd todo
npm start
スクリーンショット 2023-01-22 0.00.18.png

关闭应用程序

「复制」

创建GitHub仓库

在GitHub上创建一个存储库,并将应用程序推送到该存储库中。

git init
git remote add origin https://github.com/xxxxx/todo.git
git remote -v
git add .
git commit -m 'init'
git push origin main
    • 【GitHub】 authentication failedで失敗する場合は以下を参考にトークンを設定する

 

    https://donachikiblog.com/github-authentication-failed/

增强部署

使用AWS账号登录,从Amplify控制台部署应用程序。

スクリーンショット 2023-01-22 0.44.22.png

放大应用程序的初始化

安装 Amplify CLI

npm install -g @aws-amplify/cli

设置Amplify

    この際、AWSにてAmplifyでアクセスするIAMユーザを作成する必要があるのでアナウンスに記載されるURLをもとにIAMユーザを作成し、accessKeyIdとSecretAccessKeyを発行後、ローカルコンソール上に入力する
amplify configure
・
・
・
Sign in to your AWS administrator account:
https://console.aws.amazon.com/
Press Enter to continue

Specify the AWS Region
? region:  ap-northeast-1
Specify the username of the new IAM user:
? user name:  todoAdmin
Complete the user creation using the AWS console
https://console.aws.amazon.com/iam/home?region=*****
Press Enter to continue

Enter the access key of the newly created user:
? accessKeyId:  ********
? secretAccessKey:  ********
This would update/create the AWS Profile in your local machine
? Profile Name:  default

Successfully set up the new user.

初始化Amplify项目

amplify init --appId 【AmplifyのアプリケーションARN】

增加认证

安装amplify库

npm install aws-amplify @aws-amplify/ui-react

将认证服务添加到Amplify项目中。

amplify add auth

部署身份验证服务

    「–y」オプションで全ての質問に「yew」を設定する
amplify push --y

修改React应用

src/index.js 的源代码

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Amplify } from 'aws-amplify'
import config from './aws-exports';
Amplify.configure(config);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

src/App.js:
主要原始碼/src/App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';
import { withAuthenticator } from '@aws-amplify/ui-react'
import '@aws-amplify/ui-react/styles.css';

function App({ signOut, user }) {
return (
<div className="App">
<header>
<img src={logo} className="App-logo" alt="logo" />
<h1>Hello {user.username}</h1>
<button onClick={signOut}>Sign out</button>
</header>
</div>
);
}
export default withAuthenticator(App);
スクリーンショット 2023-01-22 1.29.03.png

创造GraphQL

将GraphQL API添加到应用程序中。

amplify add api
? Select from one of the below mentioned services: GraphQL
? Here is the GraphQL API that we will create. Select a setting to edit or continue Continue
? Choose a schema template: Single object with fields (e.g., “Todo” with ID, name, description)
✔ Do you want to edit the schema now? (Y/n) · yes
? Try opening with system-default editor instead? Yes

修改GraphQL文件
– 修改amplify/backend/api/todo/schema.graphql文件

type Note @model {
  id: ID!
  name: String!
  description: String
}

撰写用于使用API的前端代码。

    src/App.jsを更新
import React, { useState, useEffect } from 'react';
import logo from './logo.svg';
import './App.css';
import { withAuthenticator } from '@aws-amplify/ui-react'
import '@aws-amplify/ui-react/styles.css';
import { API } from 'aws-amplify';
import { listNotes } from './graphql/queries';
import { createNote as createNoteMutation, deleteNote as deleteNoteMutation } from './graphql/mutations';

const initialFormState = { name: '', description: '' }

function App({ signOut, user }) {
  const [notes, setNotes] = useState([]);
  const [formData, setFormData] = useState(initialFormState);

  useEffect(() => {
    fetchNotes();
  }, []);

  async function fetchNotes() {
    const apiData = await API.graphql({ query: listNotes });
    setNotes(apiData.data.listNotes.items);
  }

  async function createNote() {
    if (!formData.name || !formData.description) return;
    await API.graphql({ query: createNoteMutation, variables: { input: formData } });
    setNotes([ ...notes, formData ]);
    setFormData(initialFormState);
  }

  async function deleteNote({ id }) {
    const newNotesArray = notes.filter(note => note.id !== id);
    setNotes(newNotesArray);
    await API.graphql({ query: deleteNoteMutation, variables: { input: { id } }});
  }
  return (
    <div className="App">
      <h1>My Notes App</h1>
      <input
        onChange={e => setFormData({ ...formData, 'name': e.target.value})}
        placeholder="Note name"
        value={formData.name}
      />
      <input
        onChange={e => setFormData({ ...formData, 'description': e.target.value})}
        placeholder="Note description"
        value={formData.description}
      />
      <button onClick={createNote}>Create Note</button>
      <div style={{marginBottom: 30}}>
        {
          notes.map(note => (
            <div key={note.id || note.name}>
              <h2>{note.name}</h2>
              <p>{note.description}</p>
              <button onClick={() => deleteNote(note)}>Delete note</button>
            </div>
          ))
        }
      </div>
      <img src={logo} className="App-logo" alt="logo" />
      <h1>Hello {user.username}</h1>
      <button onClick={signOut}>Sign out</button>
    </div>
  );
}

export default withAuthenticator(App);
スクリーンショット 2023-01-22 1.53.29.png

增加供图片使用的存储空间

amplify add storage
? Select from one of the below mentioned services: Content (Images, audio, video, etc.)
✔ Provide a friendly name for your resource that will be used to label this category in the project: · imageStorage
✔ Provide bucket name: · test-amplify-image-storage-xxx
✔ Who should have access: · Auth users only
✔ What kind of access do you want for Authenticated users? · create/update, read, delete
✔ Do you want to add a Lambda Trigger for your S3 Bucket? (y/N) · no
✅ Successfully added resource imageStorage locally
⚠️ If a user is part of a user pool group, run "amplify update storage" to enable IAM group policies for CRUD operations
✅ Some next steps:
"amplify push" builds all of your local backend resources and provisions them in the cloud
"amplify publish" builds all of your local backend and front-end resources (if you added hosting category) and provisions them in the cloud

修改GraphQL文件

type Note @model {
  id: ID!
  name: String!
  description: String
  image: String
}

部署API和存储。

amplify push --y

确认动作

スクリーンショット 2023-01-22 2.04.59.png

将程序部署到正式环境

首先将更改推送到 GitHub 上的 main 分支,即可自动部署到生产环境。

git add -A
git commit -m 'main push'
git push origin main

特性标志在 “amplify/cli.json” 配置文件中定义,并且对当前运行的 Amplify CLI 是未知的问题。
当部署到生产环境时,上述错误会发生,并导致部署失败。
因此,在 Amplify 控制台的 “应用程序设置” > “构建设置” > “使用应用程序构建” 中,我修改了 amplify.yml 如下所示:

AWS Amplify Studioでのdeploy時のつまずきポイント

version: 1
backend:
  phases:
    build:
      commands:
        - '# Execute Amplify CLI with the helper script'
        - amplifyPush --simple
frontend:
  phases:
    preBuild:
      commands:
        - nvm install 16.13.1
        - nvm use  16.13.1
        - npm install @aws-amplify/cli --force
        - npm install
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: build
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

另外,在“构建设置”中的“构建镜像设置”中,我们添加了包名为Amplify CLI,版本为latest的包更新。

スクリーンショット 2023-01-22 15.57.07.png

再次通过Amplify控制台进行构建,部署完成,并可以通过Amplify上的域名进行访问。

スクリーンショット 2023-01-22 15.59.39.png

最后

一旦完成了教程,以后将深入探讨React编码并进行记录。

广告
将在 10 秒后关闭
bannerAds