0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Amplify ConsleでAngularの環境設定を切り替える

Posted at

概要

Amplify ConsoleでホスティングされたAngularアプリの環境設定を切り替える方法になります。Amplify Consoleでは環境変数をブランチ単位で管理することができるため、そちらを利用してビルドプロセスをカスタムし、任意の環境でホスティングすることができます。

Angularの環境設定

Angularでは開発環境用、ステージング環境用、本番環境用などの環境固有の変数をプロジェクトに定義することができます。下記のようなディレクトリ構成で、デフォルトの設定をenvironment.tsに記載することができ、環境が指定された場合に各環境ファイルの記載された内容で上書きされます。

└──myProject/src/environments/
                      └──environment.ts
                      └──environment.prod.ts
                      └──environment.stage.ts

angular.jsonには次のようにconfigurations配下に設定を追加します。

angular.json
"configurations": {
  "prod": { ... },
  "stage": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.stage.ts"
      }
    ]
  }
}

stage環境設定を使ってビルドする際は以下のように--configuration=stageとオプションを指定してbuildを実行します。

ng build --configuration=stage

Amplify Consoleの環境変数

冒頭でお話しした通り、Amplify Console上で環境変数の設定から任意の名前で環境名を追加します。その後アクションから「変数の上書きを追加する」を押下し、任意のブランチでデプロイしたいAngularの環境名を追加します。下記画像は「backup」ブランチにstage環境の設定を追加しています。
image.png

ビルドプロセス

Amplifyのビルド設定を修正します。amplify.yml上のbuildコマンドに、ng build -c ${env}と指定すれば、先ほど指定したブランチ、環境変数でAngularアプリケーションのホスティングを実行できます。

amplify.yml
version: 1
frontend:
  phases:
    preBuild:
      commands:
        - echo ${env}
        - npm install
        - npm install -g @angular/cli@12.1.4
    build:
      commands:
        - ng build -c ${env}
  artifacts:
    baseDirectory: dist/ElectricWeb
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

参考

https://angular.jp/guide/build
https://docs.aws.amazon.com/ja_jp/amplify/latest/userguide/environment-variables.html

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?