AWS Amplify Console で素の React アプリをホスティングしてみよう

2020-05-11
デベロッパーのためのクラウド活用方法

Author : 塚田 朗弘

読者の皆さまの中に「あー、Reactでアプリ書いたけど、なんか手軽にホスティングする方法ってないのかなー。仮想サーバー立てるのはちょっと面倒なんだよなー」と思っている方はいませんか?

この記事ではそんなあなたのために、ただただシンプルに、素の React アプリを AWS Amplify Console でホスティングする方法をご紹介します。

※ AWS Amplify のライブラリをバリバリ使ってアプリ自体を便利に開発していく話は今後書いていきます。

AWS Amplify とは

AWS Amplify はモバイルネイティブアプリ、Web(JavaScript)アプリを開発するためのフレームワークおよびサービスです。

  • Amplify Framework
    • クライアントライブラリ(JavaScript)
    • UI コンポーネント
    • Amplify CLI

  • Developer Tool
    • Amplify Console


JavaScript アプリは React & React Native、Angular、Ionic、Vue で書き、Amplify Consoleでホスティングすることができます。

モバイルアプリは iOS, Android 向けのライブラリがプレビュー版として提供されています(2020 年 3 月 31 日現在)。

Amplify CLI のインストールと React プロジェクトの初期設定

Amplify CLI をインストールします。

$ npm install -g @aws-amplify/cli
$ amplify -v
4.17.2
$ amplify help


| Category      |
| ------------- |
| analytics     |
| api           |
| auth          |
| function      |
| hosting       |
| interactions  |
| notifications |
| predictions   |
| storage       |
| xr            |

 █████╗ ███╗   ███╗██████╗ ██╗     ██╗███████╗██╗   ██╗    ███████╗██████╗  █████╗ ███╗   ███╗███████╗██╗    ██╗ ██████╗ ██████╗ ██╗  ██╗
██╔══██╗████╗ ████║██╔══██╗██║     ██║██╔════╝╚██╗ ██╔╝    ██╔════╝██╔══██╗██╔══██╗████╗ ████║██╔════╝██║    ██║██╔═══██╗██╔══██╗██║ ██╔╝
███████║██╔████╔██║██████╔╝██║     ██║█████╗   ╚████╔╝     █████╗  ██████╔╝███████║██╔████╔██║█████╗  ██║ █╗ ██║██║   ██║██████╔╝█████╔╝
██╔══██║██║╚██╔╝██║██╔═══╝ ██║     ██║██╔══╝    ╚██╔╝      ██╔══╝  ██╔══██╗██╔══██║██║╚██╔╝██║██╔══╝  ██║███╗██║██║   ██║██╔══██╗██╔═██╗
██║  ██║██║ ╚═╝ ██║██║     ███████╗██║██║        ██║       ██║     ██║  ██║██║  ██║██║ ╚═╝ ██║███████╗╚███╔███╔╝╚██████╔╝██║  ██║██║  ██╗
╚═╝  ╚═╝╚═╝     ╚═╝╚═╝     ╚══════╝╚═╝╚═╝        ╚═╝       ╚═╝     ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝     ╚═╝╚══════╝ ╚══╝╚══╝  ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝

amplify <command> <subcommand>

  init                Initializes a new project, sets up deployment resources in the cloud, and makes your project ready for Amplify.
  configure           Configures the attributes of your project for amplify-cli, such as switching front-end framework and adding/removing cloud-provider plugins.
  push                Provisions cloud resources with the latest local developments.
  pull                Fetch upstream backend environment definition changes from the cloud and updates the local environment to match that definition.
  publish             Executes amplify push, and then builds and publishes client-side application for hosting.
  serve               Executes amplify push, and then executes the project's start command to test run the client-side application locally.
  status              Shows the state of local resources not yet pushed to the cloud (Create/Update/Delete).
  delete              Deletes all of the resources tied to the project from the cloud.
  <category> add      Adds a resource for an Amplify category in your local backend
  <category> update   Update resource for an Amplify category in your local backend.
  <category> push     Provisions all cloud resources in a category with the latest local developments.
  <category> remove   Removes a resource for an Amplify category in your local backend.
  <category>          Displays subcommands of the specified Amplify category.
  mock                Run mock server for testing categories locally.
  codegen             Generates GraphQL statements(queries, mutations and eventHandlers) and type annotations.
  env                 Displays and manages environment related information for your Amplify project.
  console             Opens the web console for the selected cloud resource.

amplify configure で Amplify CLI の初期設定を行い、npx create-react-app で React プロジェクトを作成します。

$ amplify configure
(snip)
$ npx create-react-app myapp2020
$ cd myapp2020
$ npm start

はい、これで React アプリができましたね。

次に amplify init でプロジェクトを Amplify 用に初期化します。

$ amplify init
? Enter a name for the project myapp2020
? Enter a name for the environment dev
? Choose your default editor: Vim (via Terminal, Mac OS only)
? Choose the type of app that you're building javascript
Please 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

(snip)

Adding backend environment dev to AWS Amplify Console app: dilgvpwauepwn
⠦ Initializing project in the cloud...

CREATE_IN_PROGRESS UnauthRole              AWS::IAM::Role             Mon Mar 31 2020 09:20:48 GMT+0900 (Japan Standard Time) Resource creation Initiated
CREATE_IN_PROGRESS AuthRole                AWS::IAM::Role             Mon Mar 31 2020 09:20:48 GMT+0900 (Japan Standard Time) Resource creation Initiated
CREATE_IN_PROGRESS DeploymentBucket        AWS::S3::Bucket            Mon Mar 31 2020 09:20:48 GMT+0900 (Japan Standard Time) Resource creation Initiated
CREATE_IN_PROGRESS UnauthRole              AWS::IAM::Role             Mon Mar 31 2020 09:20:48 GMT+0900 (Japan Standard Time)
CREATE_IN_PROGRESS AuthRole                AWS::IAM::Role             Mon Mar 31 2020 09:20:48 GMT+0900 (Japan Standard Time)
CREATE_IN_PROGRESS DeploymentBucket        AWS::S3::Bucket            Mon Mar 31 2020 09:20:47 GMT+0900 (Japan Standard Time)
CREATE_IN_PROGRESS amplify-myapp-dev-42039 AWS::CloudFormation::Stack Mon Mar 31 2020 09:20:44 GMT+0900 (Japan Standard Time) User Initiated
⠧ Initializing project in the cloud...

(snip)

CREATE_COMPLETE amplify-myapp-dev-42039 AWS::CloudFormation::Stack Mon Mar 31 2020 09:21:11 GMT+0900 (Japan Standard Time)
✔ Successfully created initial AWS cloud resources for deployments.
✔ Initialized provider successfully.
Initialized your environment successfully.

(snip)

Hosting 機能の追加と Publish

Amplify CLI では、いろいろな機能を "amplify add" コマンドでプロジェクトに追加できます。
"amplify help" コマンドで表示される Category が利用できる機能リストです。

Category
analytics
api
auth
function
hosting
interactions
predictions
storage
xr

今回はホスティングを行いたいので、そのままズバリ hosting を追加します。

$ amplify add hosting
? Select the plugin module to execute (Use arrow keys)
? Hosting with Amplify Console (Managed hosting with custom domains, Continuous deployment)
? Choose a type Manual deployment

You can now publish your app using the following command:

Command: amplify publish

Amazon CloudFrontAmazon S3 を使ってホスティングすることもできるのですが、今回は CI/CD やデプロイ後のキャッシュ削除などの機能が利用できる Hosting with Amplify Console を、そして amplify publish コマンドで手軽にアプリを publish できる Manual deployment を選びます。

ここで amplify console コマンドを叩くと、このアプリの管理コンソールがブラウザで立ち上がります。

Amplify Console でホスティングする準備ができました。
amplify publish でアプリをアップロードしてみましょう!

$ amplify publish
✔ Successfully pulled backend environment dev from the cloud.

Current Environment: dev

| Category | Resource name  | Operation | Provider plugin   |
| -------- | -------------- | --------- | ----------------- |
| Hosting  | amplifyhosting | Create    | awscloudformation |
? Are you sure you want to continue? Yes
⠦ Updating resources in the cloud. This may take a few minutes...

(snip)

✔ All resources are updated in the cloud


Publish started for amplifyhosting

> myapp2020@0.1.0 build /Path/to/myapp2020
> react-scripts build

Creating an optimized production build...
Compiled successfully.

File sizes after gzip:

  39.39 KB  build/static/js/2.560e4ef9.chunk.js
  770 B     build/static/js/runtime-main.0bbf322e.js
  646 B     build/static/js/main.6fcf60da.chunk.js
  547 B     build/static/css/main.5f361e03.chunk.css

The project was built assuming it is hosted at /.
You can control this with the homepage field in your package.json.

The build folder is ready to be deployed.
You may serve it with a static server:

  yarn global add serve
  serve -s build

Find out more about deployment here:

  bit.ly/CRA-deploy

✔ Zipping artifacts completed.
✔ Deployment complete!
https://dev.d2z9z6vvlc6d0d.amplifyapp.com

これで React アプリのビルド成果物が zip に固められ、Amplify Console へのデプロイが行われました。
最後に表示されている URL にアクセスしてみましょう。

できました!

これで後は何か変更を加えたら amplify publish コマンドを実行すれば再デプロイできます。
また、 amplify console で開く管理コンソールからは、カスタムドメインやアクセス制御( Basic 認証)の設定も行うことができます。

ぜひお手元の React アプリを Amplify Console でホスティングしてみてください!

その他にも色々便利な AWS Amplify を使ってみてください

今回はとにかく「簡単に JavaScript アプリのホスティング・公開ができるんだ!!」ということを示したく、他のことを一切行わなかったのですが、もちろんこれ以外にも色々な機能を提供しています(認証機能を付けたり、GraphQL でリアルタイムにメッセージングしたり、ユーザー動向を分析したり、AI 機能を組み込んだり…などなど)。

今後そういった記事も増やしていきたいと考えていますが、興味のある方はぜひ AWS Amplify のチュートリアルなどのご覧いただき触ってみてください!


builders.flash メールメンバーへ登録することで
AWS のベストプラクティスを毎月無料でお試しいただけます

筆者プロフィール

塚田 朗弘
アマゾン ウェブ サービス ジャパン合同会社
主に Startup のお客様を支援するソリューションアーキテクト。AWS Amplify は可愛い。

AWS を無料でお試しいただけます

AWS 無料利用枠の詳細はこちら ≫
5 ステップでアカウント作成できます
無料サインアップ ≫
ご不明な点がおありですか?
日本担当チームへ相談する